C#消息框显示

时间:2016-04-07 15:45:38

标签: c# messagebox

下面的代码是一个应该在字段中查找任何文本的表单,如果没有找到文本,它应该显示一个消息框,让他们再次尝试。代码如下:

if (string.IsNullOrWhiteSpace(OrderField.Text))
{
    MessageBox.Show("Please input Order Number");
}
else
{
    MessageBox.Show("Derp");
}
if (string.IsNullOrWhiteSpace(BoxField.Text))
{
    MessageBox.Show("Please input Number of Boxes");

}
else
{
    MessageBox.Show("Derp");
}

2 个答案:

答案 0 :(得分:1)

我建议提取方法

using System.Linq;

...

private static Boolean IsControlValid(Control control) {
  if (!String.IsNullOrWhiteSpace(control.Text))
    return true;

  // Let's be nice: put key board focus to the control 
  if (control.CanFocus)
    control.Focus();

  MessageBox.Show(String.Format("Please input number at {0}.", control.Name));

  return false; 
}

...

private void SaveAndClose() {
  // Put here all controls to be tested
  Control[] controls = new Control[] {
    OrderField,
    BoxField,
  };

  // do we have any controls that should be filled in?
  if (controls.Any(control => !IsControlValid(control))) 
    return; 

  ...
  // all controls are valid; so save/send the data
  ...

  Close(); // close the form
}

答案 1 :(得分:0)

我认为如果任何输入有空值,你想要验证表单吗? 在表单中循环所有TextInput控件,您应该通过Tag属性为每个文本框设置所需的友好名称:

foreach(Control c in this.Controls) {
   if(c is TextBox) {
      var textbox = c as TextBox;
      if(string.IsNullOrEmpty(textbox.Text)) {
         MessageBox.Show(textbox.Tag.ToString() + " is empty");
      }
   }
}