我目前有一个WinForm,包括姓名,地址,邮政编码,州和年龄。
用户输入数据后,单击“退出”按钮确认没有字段为空,然后将数据保存到文件中。我想添加一个Zip Code验证,确认文本框(ZipField)只包含数字。
private void Btn_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(NField.Text) || String.IsNullOrEmpty(AField.Text) ||
String.IsNullOrEmpty(ZField.Text) || String.IsNullOrEmpty(SField.Text) ||
String.IsNullOrEmpty(AField.Text))
{
MessageBox.Show("Please complete", "Unable to save", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
saveInfo();
Form myForm = Start.getForm();
myForm.Show();
this.Close();
}
答案 0 :(得分:4)
请参阅:http://www.codeproject.com/Articles/13338/Check-If-A-String-Value-Is-Numeric
public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
Double result;
return Double.TryParse(val,NumberStyle,
System.Globalization.CultureInfo.CurrentCulture,out result);
}
编辑:
用法
private void saveAndExitBtn_Click(object sender, EventArgs e)
{
if (!isNumeric(custZipField.Text, System.Globalization.NumberStyles.Integer))
{
MessageBox.Show("Please enter a valid post code", "Unable to save", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
if (String.IsNullOrEmpty(custNameField.Text) || String.IsNullOrEmpty(custAddressField.Text) ||
String.IsNullOrEmpty(custZipField.Text) || String.IsNullOrEmpty(custStateField.Text) ||
String.IsNullOrEmpty(custAgeField.Text))
{
MessageBox.Show("Please complete the entire form", "Unable to save", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
//save the data
saveNewCustomerInfo();
//next, retrieve the hidden form's memory address
Form myParentForm = CustomerAppStart.getParentForm();
//now that we have the address use it to display the parentForm
myParentForm.Show();
//Finally close this form
this.Close();
}//end saveAndExitBtn_Click method
public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
Double result;
return Double.TryParse(val, NumberStyle,
System.Globalization.CultureInfo.CurrentCulture, out result);
}
答案 1 :(得分:0)
从技术上讲,你可以在其他方面进行快速验证:
try
{
var zipCode = Convert.ToInt32(custZipField.Text);
}
catch () // Invalid input and such
但是,我建议您创建模型类来保存所有这些属性(名称,地址,年龄,邮政编码等),并有一个名为IsValid的方法,您可以在其中验证所有这些并做出相应的反应。
编辑:
根据Zeb的回答,你可以使用TryParse:
int result;
var isNumeric = Int32.TryParse(custZipField.Text, out result);
答案 2 :(得分:0)
这没有任何尝试捕获。
Int32 zipCode = 0;
Int32.TryParse(custZipField.Text , out zipCode);
如果zipCode
为零,则custZipField.Text
为空或不是数字