Alexander Song Alexander Song - 3 months ago 16
C# Question

Having a blank textbox crashes the program when i press the login button

Beginner programmer. I have a login button, it works completely fine when I enter the right credentials, but when I click the login button while having an empty textbox the program crashes and gives me "An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll". I tried using != null in the else if but that didn't work either. So my question is how would I be able to get an empty textbox displaying "Please enter a valid username and/or password" instead of crashing the program? Thanks!

Additional information: Input string was not in a correct format.

private void btnLogin_Click(object sender, EventArgs e)
{
Entities2 db = new Entities2();
foreach (var usert in db.Teachers)
{
if (usert.TID == Convert.ToInt32(txtLogin.Text) && usert.Password == txtPassword.Text)
{
Teach teacher = new Teach();
teacher.ShowDialog();
}
else if (usert.TID != Convert.ToInt32(txtLogin.Text) && usert.Password != txtPassword.Text)
{
MessageBox.Show("Please Enter a Valid Username and/or Password");
}
}
}

Answer
private void btnLogin_Click(object sender, EventArgs e)
{
   try
   {
       if(txtLogin.Text!="" && txtPassword.Text!="")
       {
          Entities2 db = new Entities2();
          foreach (var usert in db.Teachers)
          {
             if (usert.TID == Convert.ToInt32(txtLogin.Text) &&  usert.Password == txtPassword.Text)
            {
                Teach teacher = new Teach();
                teacher.ShowDialog();
            }
            else if (usert.TID != Convert.ToInt32(txtLogin.Text) && usert.Password != txtPassword.Text)
            {
                MessageBox.Show("Please Enter a Valid Username and/or Password");
            }
        }
      else
      {
         if(txtLogin.Text=="")
         {
            MessageBox.Show("Please Enter a Username");
         }
         else if(txtPassword.Text=="") 
         {
            MessageBox.Show("Please Enter a  Password");
         }
      }
    }
    Catch(Exception ex)
    {
       MessageBox.Show("Please Enter a  Valid Username and/or Password");
    }
}

And moreover this is not proper way to check and match the UserName Password. You can instead use the following approach

if(txtLogin.Text!="")
   {
      Entities2 db = new Entities2();
      Teacher Tobj=db.Teachers.where(x=>x.TID==Convert.ToInt32(txtLogin.Text) && x.Password==txtPassword.Text).SingleOrDefault();
        if (Tobj!=null)
        {
            Teach teacher = new Teach();
            teacher.ShowDialog();
        }
        else
        {
            MessageBox.Show("Please Enter a Valid Username and/or Password");
        }
   }
Comments