简体   繁体   中英

Most efficient way to see if any of textBoxes are empty C#

I have a webform that can have multiple text boxes.

Lets say 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! First part Me.Controls.OfType(Of TextBox)() gets all the textboxes on the form, the Any function check a condition.

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.

Use String.IsNullOrWhiteSpace instead of triming and than comparing value with empty string. Remember String.IsNullOrWhiteSpace is available with .Net framework 4.0 or higher.


Another option would be have these specific textboxes in a group control like Panel and then can use

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 . In the code behind, do what you did but just make one if statement that chacks the textbox with the ID in the control

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM