2014-06-14 72 views
0

我是初学C#的学习者。如果我有2个文本框,我可以验证1个if语句中的2个文本框吗?多文本框验证

例如:

{ 
    string emptytextbox 
    if (textBox1.Text == "" || textBox2.Text == "" || textBox3.text == "") 
    { 
     //if textbox2 is empty, then messagebox will show 
     emptytextbox = textBox2.text; 
     mbox(emptytextbox + " must be filled"); 

     //messagebox will show "textBox2 must be filled" 
     //but if textbox1&2 has ben filled, but textbox3 empty,then messagebox will show "textbox3 must be filled" 
    } 
} 

我能做到这一点?

+0

做到这要看你的需求。如果你想在两个文本框都为空时执行一些动作,那么你可以有一个if语句,否则你需要多个嵌套或单独的if条件。 – Hassan

+0

有更好的方法来实现这个功能。你在使用Windows窗体应用程序吗? – Hassan

回答

1

一个条件返回一个布尔值,没有办法知道女巫是一个空的文本框。当您编写或表达式时,如果任何组件评估为true,则条件评估为true。在这种情况下,当你进入条件时,事实是至少有一个条件是真的(条件是我的意思是textBox1.Text == "")。

在这种情况下执行验证的必须是这样的最佳方式:

void VerificationFunction() 
    { 
     CheckTextBox(textbox1); 
     CheckTextBox(textbox2); 
     CheckTextBox(textbox3); 
    } 

void CheckTextBox(TextBox tb) 
    { 
     if (string.IsNullOrEmpty(tb.Text)) 
     { 
      MessageBox.Show(tb.Name + "must be filled"); 
     } 
    } 
+0

正确发布您的代码 –

0

我可以确认在1 2文本“if”语句?

NO。因为您必须检查每个文本框并通知用户有关特定文本框的内容为空。

对于所有三个文本框,你可以做这样的事情:

if (textBox1.Text == "")  
    MessageBox.Show("textBox1 must be filled"); 
if (textBox2.Text == "")  
    MessageBox.Show("textBox2 must be filled"); 
if (textBox3.Text == "")  
    MessageBox.Show("textBox3 must be filled"); 

这是很好的做法,为目的的一种方法。


这里是可用于检查表单上的每个文本框的方法。如果有任何空文本框,它会向用户显示消息textbox must be filled。良好的做法是通知用户一次。

private void ValidateTextBoxes() 
    { 
     foreach (Control c in this.Controls) 
     { 
      if (c is TextBox) 
      { 
       if (string.IsNullOrEmpty(c.Text)) 
       { 
        MessageBox.Show(c.Name + " must be filled"); 
        break; 
       } 

      } 
     } 
    } 
0

最好的办法是单独

if (String.IsNullOrEmpty(textBox1.Text)) 
{ 
    textBox1.BorderBrush = System.Windows.Media.Brushes.Red; 
} 
if (String.IsNullOrEmpty(textBox2.Text)) 
{ 
    textBox2.BorderBrush = System.Windows.Media.Brushes.Red; 
} 

enter image description here