I am a c# learner and need your help. Thanks in advance. I am working on this multi-user single login form. I have connected to SQL local database with the following as the columns: UserID, Password, UserType
My problem is, the code below works fine as long as these three are correct. If I provide a wrong password for example, nothing happens.
It has to be an issue with the "Else" part of my code, but I have tried so many changes I have even lost track of when I was close to making it work. Please help. To restate my expectations of the project: 1.When I select Admin or Student from combobox(cmbusertype) and provide INcorrect userid and password, I should get an incorrect credentials error message and number of attempts left.After 3 attempts, login button should be grayed out and I am prompted to reset my password.
public partial class Loginsystem : Form
{
public Loginsystem()
{
InitializeComponent();
}
int attempts =1;
private void btnlogin_Click(object sender, EventArgs e)
{
if (cmbusertype.SelectedItem == null)
{
MessageBox.Show("Please select User Type to continue...");
cmbusertype.Focus();
return;
}
if (txtuserid.Text == "")
{
MessageBox.Show("Please enter your UserID...");
txtuserid.Focus();
return;
}
if (txtpassword.Text == "")
{
MessageBox.Show("Please enter your password...");
txtpassword.Focus();
return;
}
try
{
SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLlocaldb; Initial Catalog = AdminAuthentication; Integrated Security = True"); ;
SqlCommand cmd = new SqlCommand("select * from SimplifyLogin where userID='" + txtuserid.Text + "' and password='" + txtpassword.Text + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
string cmbItemValue = cmbusertype.SelectedItem.ToString();
if (dt.Rows.Count >0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["UserType"].ToString() == cmbItemValue) //you can use 2 instead of usertype in that index because usertype column is in 2 index
{
if (cmbusertype.SelectedIndex == 0)
{
MessageBox.Show("You are logged in as " + dt.Rows[i][2]);
MessageBox.Show("Displaying Admin Dashboard");
this.Hide();
}
else
{
MessageBox.Show("Welcome Student! Displaying Exam Options");
this.Hide();
}
}
else
{
MessageBox.Show("Invalid username and/or Password.Please try again. \nAttempts: " + attempts + "out of of 3");
txtpassword.Clear();
attempts++;
}
if (attempts == 4)
{
MessageBox.Show("You have reached maximum login attempts. Click 'Forgot Password' below to reset it.");
btnlogin.Enabled = false;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}