Anon Anon - 3 months ago 7
C# Question

Won't show the validation message

When the user enters nothing, the error message does not display. It just does nothing. Have I put the else message in the wrong place?



private void btnLogin2_Click(object sender, EventArgs e)
{

if (txtLogin2.Text != "" && txtPassword2.Text != "")
{
int AID = Convert.ToInt32(txtLogin2.Text);
Entities2 db = new Entities2();
Administrator admin = db.Administrators.Where(x => x.AID == AID && x.Password == txtPassword2.Text).SingleOrDefault();
if (admin != null)
{
Admin admini = new Admin();
admini.ShowDialog();
}
else
{
int value;
if (int.TryParse(txtLogin2.Text, out value)) {
MessageBox.Show("User ID not in valid format");
}
if (txtLogin2.Text == "" )
{
MessageBox.Show("Please enter a User ID");
}
if (txtPassword2.Text == "") {
MessageBox.Show("Please enter a valid Password");
}
}
}
}




Answer

When the user enters nothing

Then the first if statement evaluates to false:

if (txtLogin2.Text != "" && txtPassword2.Text != "")

Which means none of the code in this function would be reached. You probably want to put these at the start of the function:

if (txtLogin2.Text == "" )
{
    MessageBox.Show("Please enter a User ID");
}
if (txtPassword2.Text == "") {
    MessageBox.Show("Please enter a valid Password");
}
if (txtLogin2.Text != "" && txtPassword2.Text != "")
{
    //... the rest of the code, minus the if statements above
}
Comments