[英]How to cancel Button click action when required fields are empty?
我有两种形式的程序。 其中一个检查空字段,第二个插入记录。
private void CheckNullValues()
{
if (textBox1.Text == "") {
MessageBox.Show("Field [Email] can not be empty","Information",MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Focus();
return();
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
CheckNullValues();
MessageBox.Show("Insert record");
}
如果textBox1为空并且不让其显示MessageBox.Show("Insert record")
如何停止执行CheckNullValues
过程中的操作?
您需要将CheckNullValues
方法的类型更改为bool
,以便根据TextBox是否为空而返回true或false值。
您可能还想将其名称更改为反映返回值的名称。 我通常使用这样的东西:
private bool ValidInputs()
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Field [Email] can not be empty","Information",
MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Focus();
return false;
}
if (string.IsNullOrEmpty(textBox2.Text))
{
// ...
return false;
}
return true;
}
然后,在您的按钮单击事件中,您可以轻松地执行以下操作:
if (!ValidInputs()) return;
此外,为避免在ValidInputs()
方法中重复代码,可以将用于验证TextBox内容的逻辑移到单独的方法中:
public bool TextBoxEmpty(TextBox txtBox, string displayMsg)
{
if (string.IsNullOrEmpty(txtBox.Text))
{
MessageBox.Show(displayMsg, "Required field",
MessageBoxButtons.OK, MessageBoxIcon.Information);
txtBox.Focus();
return true;
}
return false;
}
这样,您的ValidInputs()
方法将变为:
private bool ValidInputs()
{
if (TextBoxEmpty(textBox1, "Field [Email] can not be empty")) return false;
if (TextBoxEmpty(textBox2, "Some other message")) return false;
// ...
return true;
}
如果将检查某物是否为null的函数设置为返回true或false,则可以在click事件中使用if语句。
if (!checkForNulls()) {
MessageBox.Show("Insert record");
}
请按如下所示修改您的代码:private bool CheckNullValues(){
if (textBox1.Text == "")
{
MessageBox.Show("Field [Email] can not be empty", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Focus();
return false;
}
else
{
return true;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
if (CheckNullValues())
{
MessageBox.Show("Insert record");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.