简体   繁体   English

C# If/else 语句不起作用

[英]C# If/else statement not working

I have an if/else statement that is not working.我有一个 if/else 语句不起作用。

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.如果 Permission 与 Exec 相等,则一切正常,但是(在逐步执行代码时)我注意到,当 Permission 不等于 Exec 时,它不会触发 Else。 It just goes back to the while statement and stops.它只是回到 while 语句并停止。 Let me know if I need to provide any more code.如果我需要提供更多代码,请告诉我。

Note: I only have Exec in the database.注意:我在数据库中只有 Exec 。 Everything else is null.其他一切都是空的。

I have noticed that when Permission does not equal Exec, it does not trigger the Else.我注意到当 Permission 不等于 Exec 时,它不会触发 Else。

I have a very hard time believing that.我很难相信这一点。 Please show us the exact contents of permission when it does not equal "Exec" .当它不等于"Exec"时,请向我们展示permission的确切内容。

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.这是因为您不允许Windows 消息循环处理消息。 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.因此,即使Visible属性设置为 true, WM_PAINT消息也不会被处理(直到您的循环退出),因此您的控件的外观不会改变。

EDIT:编辑:

As Brian Gideon points out in a comment, your executable version may be out of sync with your code.正如 Brian Gideon 在评论中指出的那样,您的可执行版本可能与您的代码不同步。 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 "Exec" == "Exec" 会失败

Try尝试

string permission = rdr["Permission"].ToString().Trim();字符串权限 = rdr["权限"].ToString().Trim();

Basically it's an if else statement like stated:基本上它是一个if else语句,如下所示:

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.此外,您可以执行多个if语句,如果它们都不是相对true您可以让它们都指向else语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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