ASP.NET How to retrieve a list of the empty labels on a page?
I have some labels on my Page (e.g. Label1...Label100).
I don't want to loop through all Labels to check if Text property is = "" (or string.Empty, whatever), so this's my question - is it possible to use LINQ开发者_开发知识库 or Lambda Expression to get all "empty" labels ?
You can find all the page controls through the Controls
property
Page.Controls.OfType<Label>().Where(lbl => lbl.Text == "");
Note that this isn't recursive; i.e. if you have a PlaceHolder
which has controls of its own, those will not be returned by Page.Controls
.
You can make a "FindAllChildren" extension method that finds all controls recursively from some parent control (which could be the page), and have it return an IEnumerable<Control>. Then use a Linq query on that.
public static IEnumerable<Control> FindAllChildren(this Control control)
{
foreach(Control c in control.Controls)
{
yield return c;
foreach(control child in c.FindAllChildren()
yield return child;
}
}
var allEmptyLabels = parent.FindAllChildren().OfType<Label>()
.Where(l => l.Text == String.Empty);
Is that your label naming convention?
If so, this quick and dirty method could do:
List<Label> labels = new List();
for (int i = 0; i <= 100; i++)
{
var label = (Label)Page.FindControl("Label" + i);
if (label.Text != string.Empty)
labels.Add(label);
}
// use labels collection here
No LINQ, or Lambdas, but it's another perspective for you.
精彩评论