我有一個單擊事件處理程序,它必須檢查兩個文本框是否爲空,如果兩者都不是值賦給兩個變量並傳遞給另一個方法。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