2013-10-20 103 views
1

我有一個C#表單,要求用戶填寫4個文本框並選擇3個組合框。我想看看是否有一種驗證所有這些字段都被填充的簡單方法。如果不是,則提供消息提示,說明哪些字段丟失。C#驗證所有字段都有值

我知道我可以使用下面的代碼,但想看看是否有別的

if (String.IsNullOrEmpty(TextBox.Text)) 
{ 
     MessageBox.Show("Enter Text Here.", "Error", MessageBoxButtons.OK, 
               MessageBoxIcon.Warning); 

} 

回答

1

你可以遍歷所有文本框的東西用abatishchev解決方案解釋here

我背誦了他在這一個:

定義的擴展方法:

public static IEnumerable<TControl> GetChildControls(this Control control) where TControl : Control 
{ 
    var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>(); 
    return children.SelectMany(c => GetChildControls(c)).Concat(children); 
} 

然後使用它是這樣的:

var allTextBoxes = this.GetChildControls<TextBox>(); 

最後循環通過他們:

foreach (TextBox tb in this.GetChildControls<TextBox>()) 
{ 
    if(String.IsNullOrEmpty(tb.Text) 
    { 
     // add textbox name/Id to array 
    } 
} 

您可以將所有文本框ID添加到集合中,並在末尾使用此集合來顯示用戶需要填寫哪些Textboex。

編輯:

foreach循環是有點誤導

您可以使用它像這樣:

foreach (TextBox tb in this.GetChildControls<TextBox>()) { ... } 

foreach (TextBox tb in allTextBoxes) { ... } 

如果你有救了它事先給一個變量。

相關問題