2012-02-26 75 views
0

我有一个表单,其中有很多文本框,并且需要填写所有文本框。在C#中,如果检查是否存在具有null或空白的字段组,我该如何处理呢?检查多个文本框,如果它们为空或空白

我熟悉string.isNullOrWhiteSpace(string here)但我不想做多重if语句,这会导致错误的代码。

我试图避免这样的事情

if(string.isNullOrWhiteSpace(string here) 
    || string.isNullOrWhiteSpace(string here) 
    || string.isNullOrWhiteSpace(string here)) 
{ 
    // do something 
} 

是否有这种类型的恶意代码修复?

回答

3

您可以查询表单(或相关容器)的控件集合并过滤文本框,并进一步查询是否有任何内容为空(没有内容应该具有空值)。例如:

var emptyTextboxes = from tb in this.Controls.OfType<TextBox>() 
        where string.IsNullOrEmpty(tb.Text) 
        select tb; 

if (emptyTextboxes.Any()) 
{ 
    // one or more textboxes are empty 
} 

您可以使用流畅的语法有效地做同样的事情。

bool isIncomplete = this.Controls.OfType<TextBox>().Any(tb => string.IsNullOrEmpty(tb.Text)); 
if (isIncomplete) 
{ 
    // do your work 
} 

对于此代码,您应该至少使用Visual Studio 2008/C#3/.NET 3.5。您的项目需要引用System.Core.dll(默认情况下应该有一个),并且您需要类文件中的using System.Linq;指令。


根据您的意见,如果您无法理解或使用linq版本,请考虑另一种方法。你当然可以在一个明确的循环中做到这一点(Linq代码最终也将是一个循环)。考虑

bool isIncomplete = false; 
foreach (Control control in this.Controls) 
{ 
    if (control is TextBox) 
    { 
      TextBox tb = control as TextBox; 
      if (string.IsNullOrEmpty(tb.Text)) 
      { 
       isIncomplete = true; 
       break; 
      } 
    } 
} 

if (isIncomplete) 
{ 

} 

最后,如果所有的文本框是在一个容器中的代码被写入。该容器可能是窗体,面板等。您将需要指向适当的容器(例如,而不是this(表单)它可能是this.SomePanel)。如果您使用的是多个嵌套容器中的控件,则需要做更多的工作来以编程方式查找它们(递归搜索,显式串联等),或者您可能只是将引用预加载到数组或其他集合中。例如

var textboxes = new [] { textbox1, textbox2, textbox3, /* etc */ }; 
// write query against textboxes instead of this.Controls 

你说你有多个组框控件。如果每个GroupBox都加载到窗体上,而不是嵌套在另一个控件中,则可能会使您开始。

var emptyTextboxes = from groupBox in this.Controls.OfType<GroupBox>() 
        from tb in groupBox.Controls.OfType<TextBox>() 
        where string.IsNullOrEmpty(tb.Text) 
        select tb; 
+0

你能进一步解释你的代码? – user962206 2012-02-26 04:10:06

+0

你有什么理解麻烦?这是使用Linq,它已经是C#和Visual Studio(2008和2010)的最后两个版本的一部分。 – 2012-02-26 04:11:25

+0

你可以查询组件?我从来不知道那里有没有在线文档?我很感兴趣我想查看更多关于查询组件的文档 – user962206 2012-02-26 04:12:08

1

这取决于你认为“坏代码”。根据您的要求,需要填写的文本框可能会有所不同。此外,即使所有的字段都需要所有的时间,你仍然想给出友好的错误信息,让人们知道他们没有填写哪个字段。取决于您如何渲染表单,有多种解决此问题的方法。既然你没有在这里指定一个非常直接的方法。

var incompleteTextBoxes = this.Controls.OfType<TextBox>() 
           .Where(tb => string.IsNullOrWhiteSpace(tb.Text)); 

foreach (var textBox in inCompleteTextBoxes) 
{ 
    // give user feedback about which text boxes they have yet to fill out 
} 
0

又一种解决方案。 这将递归地遍历整个控件树,并在所有文本框中检查空或空文本。 警告 - 如果你有一些奇特的控制不是从标准的WinForms文本框继承 - 检查将不执行

bool check(Control root,List<Control> nonFilled) 
{ 
    bool result =true; 
    if (root is TextBox && string.isNullOrEmpty(((TextBox)root).Text) ) 
    { 
    nonFilled.Add(root); 
    return false; 
    } 
    foreach(Control c in root.Controls) 
    { 
    result|=check(c,nonFilled) 
    } 
    return result; 
} 

用法:

List<Control> emptytextboxes=new List<Control>() 
    bool isOK=check(form, emptytextboxes);