2014-06-14 73 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