我有一个单击事件处理程序,它必须检查两个文本框是否为空,如果两者都不是值赋给两个变量并传递给另一个方法。C#跳过如果不为空
一个变量是一个字符串,另一个是整数。如果字符串为空,但整数不是,它将正常工作(它不应该!)。但是,如果整数为空并且String不是,它会给我一个预期的错误,因为它不应该达到那个点。
下面的代码:
private void btnInsert_Click(object sender, EventArgs e)
{
String ActorName;
int Position;
if ((txtPosition.Text != null))
{
if ((txtActorName.Text != null))
{
ActorName = txtActorName.Text;
Position = int.Parse(txtPosition.Text);
InsertIntoArrayList(ActorName, Position);
PopulateActors();
}
else
{
MessageBox.Show("Please enter an Actor Name");
return;
}
}
else
{
MessageBox.Show("Please enter a position");
return;
}
}
正如你可以看到,如果txtPosition不为空,它然后测试txtActorName。如果其中任何一个为空,则会抛出相关消息。假设两者都不为空,它将值赋给变量并将它们传递给InsertIntoArrayLIst方法,然后调用PopulateActors方法。
如果我输入演员姓名和职位,一切工作正常。只有当我不输入某个位置时,它才会错过Nothings进入的位置,然后滑到Position = int.Parse(txtPosition.Text);
行,因为txtPosition为空。
任何帮助将不胜感激!
not empty =/= not null – Raptor 2014-10-17 03:31:50