maru maru - 28 days ago 10
C# Question

Winform Login Form with userlevel

I have a table of user_data and has a column for userlevel i want access to different form for different user level access here is my source code

for example

Select username,password from user_data where username = username and password = password and userlevel = 1 - for form1

Select username,password from user_data where username = username and password = password and userlevel = 2 - for form2

if ((txtusername.Text.Trim() != "") && (txtpassword.Text.Trim() != "")) // to validate if user and pass have data

{
String passwords = encryption(txtpassword.Text.Trim());
string q = "SELECT username, password FROM user_data WHERE (UserName = '" + txtusername.Text.ToString() + "') AND (Password = '" + passwords + "');";
SqlCommand cmd = new SqlCommand(q, conn);
cmd.Parameters.AddWithValue("@Username", this.txtusername.Text.Trim());
cmd.Parameters.AddWithValue("@Password", this.txtpassword.Text.Trim());
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Successfully Login", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.ShowInTaskbar = false;
this.Hide();
Form1 shForm1 = new Form1();
shForm1.FormClosed += (_, args) => this.Close();
shForm1.ShowDialog();

}
}
if (dr.HasRows == false)
{
MessageBox.Show("Invalid Username and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

else
{
MessageBox.Show("Enter username and password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


Any idea will do I'm a beginner here at winform development
Thank you ..

Answer Source

For what you include "username, password" into select?

If you need just 'user level access', you can use this(or something like this):

string q = "SELECT **userlevel** FROM user_data WHERE (UserName = '" + txtusername.Text.ToString() + "') AND (Password = '" + passwords + "');";
SqlCommand cmd = new SqlCommand(q, conn);
cmd.Parameters.AddWithValue("@Username", this.txtusername.Text.Trim());
cmd.Parameters.AddWithValue("@Password", this.txtpassword.Text.Trim());
object obj = cmd.ExecuteScalar();
if(obj != null)
{
     if((int)obj == 1)
     {
        Window1 wnd = new Window1();
        wnd.Open();
     }
     else
     {
        Window2 wnd = new Window2();
        wnd.Open();
     }
}
else
{
   // kick
}