Reputation: 2509
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).
Upvotes: 0
Views: 1158
Reputation: 53
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
Upvotes: 0
Reputation: 700730
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() == "");
Upvotes: 2
Reputation: 223392
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(.....
Upvotes: 4
Reputation: 9024
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))
Upvotes: 4