[英]Most efficient way to see if any of textBoxes are empty C#
I have a webform that can have multiple text boxes. 我有一个可以包含多个文本框的Webform。
Lets say 3: txt1 txt2 txt3 可以说3:txt1 txt2 txt3
obviously I can write the following code: 显然我可以编写以下代码:
bool atleastOneTextboxEmpty=false;
If (txt1.Text.Tostring().Trim()=="")
{
atleastOneTextboxEmpty=true;
}
If (txt2.Text.Tostring().Trim()=="")
{
atleastOneTextboxEmpty=true;
}
If (txt3.Text.Tostring().Trim()=="")
{
atleastOneTextboxEmpty=true;
}
But i'm pretty sure there is a better way to do this( but so far I was not able to find it). 但是我很确定有更好的方法可以做到这一点(但是到目前为止我还没找到它)。
Note: In my case I'm not allowed to use required field validators and form may have more textboxes which some of them are allowed to be empty(so I can't loop though all form textboxes). 注意:在我的情况下,我不允许使用必需的字段验证器,并且表单可能具有更多文本框,其中某些文本框允许为空(因此,我无法遍历所有表单文本框)。
Lambda way! Lambda方式! First part Me.Controls.OfType(Of TextBox)()
gets all the textboxes on the form, the Any
function check a condition. 第一部分Me.Controls.OfType(Of TextBox)()
获取表单上的所有文本框, Any
函数检查条件。
Dim anyEmptyTBs = Me.Controls.OfType(Of TextBox)().Any(Function(tb) String.IsNullOrWhiteSpace(tb.Text))
Create a collection/array of textboxes and then you can do: 创建文本框的集合/数组,然后可以执行以下操作:
var textBoxCollection = new[] { txt1, txt2, txt3 };
bool atleastOneTextboxEmpty = textBoxCollection
.Any(t => String.IsNullOrWhiteSpace(t.Text));
The above will check all the textboxes in the array textBoxCollection
and check if any one of them have empty/whitespace only value. 上面的代码将检查数组textBoxCollection
中的所有文本框,并检查其中是否有仅空/空白值。
Use String.IsNullOrWhiteSpace
instead of triming and than comparing value with empty string. 使用String.IsNullOrWhiteSpace
而不是进行修剪,而不是将值与空字符串进行比较。 Remember String.IsNullOrWhiteSpace
is available with .Net framework 4.0 or higher. 请记住,.Net Framework 4.0或更高版本提供String.IsNullOrWhiteSpace
。
Another option would be have these specific textboxes in a group control like Panel
and then can use 另一个选择是将这些特定的文本框放在Panel
等组控件中,然后可以使用
yourPanel.Controls.OfType<TextBox>().Any(.....
You can write that simpler as: 您可以这样写:
bool atleastOneTextboxEmpty =
txt1.Text.Trim() == "" ||
txt2.Text.Trim() == "" ||
txt3.Text.Trim() == "";
You can also put the controls in an array and check if any is empty: 您还可以将控件放入数组中,并检查是否为空:
bool atleastOneTextboxEmpty =
new TextBox[] { txt1, txt2, txt3 }
.Any(t => t.Text.Trim() == "");
You can use the Repeater control and define a TextBox inside its . 您可以使用Repeater控件并在中定义一个TextBox。 In the code behind, do what you did but just make one if statement that chacks the textbox with the ID in the control 在后面的代码中,执行您的操作,但只执行一个if语句,该语句会使控件中具有ID的文本框无效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.