2010-11-17 145 views
4

我想要驗證用戶在提交表單之前總是在文本框中輸入一個值。但是我已經提供的支票允許用戶輸入空格並繼續提交表單。 那麼,如何把檢查,使用戶無法提交表單,如果在文本框中只有空格。Windows窗體中的文本框驗證

+0

您已經標記了問題的WinForms,但它聽起來就好像你問web表單。這是什麼? – 2010-11-17 09:46:54

回答

3

您可以製作自己的自定義驗證功能。這可能很幼稚,但不知何故,它會起作用。

private bool WithErrors() 
{ 
    if(textBox1.Text.Trim() == String.Empty) 
     return true; // Returns true if no input or only space is found 
    if(textBox2.Text.Trim() == String.Empty) 
     return true; 
    // Other textBoxes. 

    return false; 
} 

private void buttonSubmit_Click(object sender, EventArgs e) 
{ 
    if(WithErrors()) 
    { 
     // Notify user for error. 
    } 
    else 
    { 
     // Do whatever here... Submit 
    } 
} 
3

在NET4.0有一個很好的功能

if(string.IsNullOrWhiteSpace(textBox1.Text)) 
{ 
    //raise your validation exception 
} 
else { 
    //go to submit 
} 
1

它可以方便地使用此錯誤提供商的code.Error提供者,你可以在你的工具箱中找到完成。

private void btnsubmit_Click(object sender, EventArgs e) 
      { 

       if (string.IsNullOrEmpty(txtname.Text)) 
       { 

        txtname.Focus(); 
        errorProvider1.SetError(txtname, "Please Enter User Name"); 
       } 

       if (string.IsNullOrEmpty(txtroll.Text)) { 
        txtroll.Focus(); 
        errorProvider1.SetError(txtroll, "Please Enter Student Roll NO"); 
       } 
} 

這裏是輸出圖像

enter image description here