您可以查询表单(或相关容器)的控件集合并过滤文本框,并进一步查询是否有任何内容为空(没有内容应该具有空值)。例如:
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;
你能进一步解释你的代码? – user962206 2012-02-26 04:10:06
你有什么理解麻烦?这是使用Linq,它已经是C#和Visual Studio(2008和2010)的最后两个版本的一部分。 – 2012-02-26 04:11:25
你可以查询组件?我从来不知道那里有没有在线文档?我很感兴趣我想查看更多关于查询组件的文档 – user962206 2012-02-26 04:12:08