我有一個簡單的Windows窗體應用程序使用具有兩個文本框找到郵編/郊區名稱的形式:無法提交與空的文本框形式(反向驗證,並讓它提交)
- 輸入郊區名稱
- 輸入郵政編碼
如果郵政編碼(文本框)沒有輸入值的形式掛了,它不會屈從/返回值。嘗試了一些東西,但仍然失敗(FormatException是未處理的)。添加任何int值,它工作正常。
private void btnFind_Click(object sender, EventArgs e)
{
//DECLARE ARRAY
string[] arrSuburbName = new string[5];
int[] arrSuburbPC = new int[5];
//POPULATESUBURB NAME ARRAY
arrSuburbName[0] = "DEE WHY";
arrSuburbName[1] = "SYDNEY";
arrSuburbName[2] = "HURSTVILLE";
arrSuburbName[3] = "BALMAIN";
arrSuburbName[4] = "NORTH SYDNEY";
//POPULATE POSTCODE ID ARRAY
arrSuburbPC[0] = 2099;
arrSuburbPC[1] = 2000;
arrSuburbPC[2] = 2220;
arrSuburbPC[3] = 2041;
arrSuburbPC[4] = 2060;
//VARIABLES
string inputSuburb = "";
int inputPostCode = 0;
string msg = "";
//INPUT
inputSuburb = txtInputSuburb.Text.Trim();
inputPostCode = int.Parse(txtInputPostCode.Text);
//PROCESS
for (int i = 0; i < arrSuburbPC.Length; i++)
{
if (inputSuburb.ToUpper() == arrSuburbName[i])
{
msg = "Postcode for " + arrSuburbName[i] + " is: " + arrSuburbPC[i];
inputPostCode = 0;
break; //EXIT THE LOOP
}
else if (inputPostCode == arrSuburbPC[i])
{
msg = "Postcode for " + arrSuburbName[i] + " is: " + arrSuburbPC[i];
break; //EXIT THE LOOP
}
else
{
msg = "Postcode Not Found";
}
}
//OUTPUT
lblResult.Text = msg;
}
由於'txtInputPostCode.Text'中沒有值,並且您正試圖解析它,請在解析'textBox'是否具有任何值之前進行檢查,然後解析它是否具有某些值。 –
如果它是空的,你希望成爲默認值'inputPostCode'?在這種情況下,您需要使用任何條件語句,如@ J.SMTBCJ15回答,並且您不能分析空對象。 –