我有一个简单的Windows窗体应用程序,其表单有两个TextBox来查找邮政编码/郊区名称:
如果邮政编码(TextBox)没有输入值,表格将被挂断,并且不会提交/返回值。尝试了一些但仍然失败(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;
}
答案 0 :(得分:0)
为什么不使用Int.TryParse(...)而不是Int.Parse(...)?
答案 1 :(得分:0)
你有
inputSuburb = txtInputSuburb.Text.Trim();
inputPostCode = int.Parse(txtInputPostCode.Text);
但是在您附加的UI屏幕中,您提供了 OR ,因此可能会发生邮政编码为空。
您需要在代码中更改逻辑。需要考虑的事项:
您的逻辑应该有一些验证。例如,使用 try catch 构造。
也许你还应该考虑用户 NumericUpDown 控制?