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.
You can use Linq extensions methods to get all Textboxes of a Panel where the property Text is not empty:
using System.Linq;
var textboxes = panel.Controls.OfType<TextBox>().Where(c => c.Text != "");
foreach ( TextBox textbox in textboxes )
{
// ...
}
If you want to check if they are all non empty, use this:
if ( panel.Controls.OfType<TextBox>().All(c => c.Text != "") )
{
// ...
}
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.