简体   繁体   中英

C# If/else statement not working

I have an if/else statement that is not working.

while (rdr.Read())
{
  string permission = rdr["Permission"].ToString();
  if (permission == "Exec")
  {
     Run my code
  }
  else
  {
     lblErrorStart.Visible = true;
  }
}

If Permission does equal Exec then everything works fine but (when stepping through the code) I have noticed that when Permission does not equal Exec, it does not trigger the Else. It just goes back to the while statement and stops. Let me know if I need to provide any more code.

Note: I only have Exec in the database. Everything else is null.

I have noticed that when Permission does not equal Exec, it does not trigger the Else.

I have a very hard time believing that. Please show us the exact contents of permission when it does not equal "Exec" .

Also realize that setting the label to visible will not update as soon as that code is executed. This is because you are not allowing the Windows Message Loop to process messages. So even though the Visible property is set to true, a WM_PAINT message is never processed (until your loop exits), so the appearance of your control will not change.

EDIT:

As Brian Gideon points out in a comment, your executable version may be out of sync with your code. Rebuild the entire project and try it again.

Sometimes when testing exact equality, you fail based on what you do NOT see... If your data is from a record set, or other structure and the actual value is NOT trimmed(), it will fail...

"Exec " == "Exec" will fail

Try

string permission = rdr["Permission"].ToString().Trim();

Basically it's an if else statement like stated:

if(label1.Text == "True")
{
    label1.Forecolor = Color.Green;
}
else
{
    label1.Text = "ERROR!";
    label1.Forecolor = Color.Red;
}

Also, you can do multiple if statements and if none of them are relatively true you can have them all lead to the else statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM