I have several textboxes nested in a panel and I want to check if they have text or not. Although I don't want to write my code like this:
if(textbox1.Text != "" && textbox2.Text != "" ...)
{
...
}
Is there any way to automate this and improve the general quality of the code itslef?
This can be done very easily by using OfType
and All
extension methods from System.Linq
.
var panel = new Panel
{
Size = new Size(500, 500),
BackColor = Color.Red
};
panel.Controls.Add(new TextBox { Text = "Value" });
panel.Controls.Add(new TextBox { Text = "Value2" });
if (panel.Controls.OfType<TextBox>().All(x => !string.IsNullOrEmpty(x.Text)))
{
//Do something
}
The code in the if statement will only execute if all the Text properties of TextBoxes are not empty.