Melanie Melanie - 1 month ago 7
ASP.NET (C#) Question

How to get Label text from a list of controls

I want to loop through all the controls in an ASP.Net

DetailsView
and get all the
Labels
in a List. Then I want to do something to the text of each
Label
. I'm using the first answer to this question as a guide. It works fine, but I can't access the
Text
property of the
Labels
because I'm creating a List of
Controls
and
Controls
don't have a
Text
property. Here's my code:

List<Control> ControlsToCheck = GetAllLabelControls(dvPurchaseOrder).ToList();
foreach (Control c in ControlsToCheck)
{
c.Text = HighlightSearchTerms(c.Text, Request.QueryString["searchstring"]);
}

public static IEnumerable<Control> GetAllLabelControls(Control parent)
{
foreach (Control control in parent.Controls)
{
if (control is Label)
yield return control;
foreach (Control descendant in GetAllLabelControls(control))
{
if (descendant is Label)
yield return descendant;
}
}
}


In the debugger, I can see the
Text
of each
Control
, but my line

c.Text = HighlightSearchTerms(c.Text, Request.QueryString["searchstring"]);


won't compile:


System.Web.UI.Control does not contain a definition for Text and no
extension method accepting a first argument of type
System.Web.UI.Control could be found.


BTW, if I use the exact syntax suggested in the link I reference above,

List<Control> ControlsToCheck = GetAllControls(dv).OfType<Label>().ToList();


I get an error message:


Cannot implicitly convert type
System.Collections.Generic.List to
System.Collections.Generic.List


How can I get the
Text
of the
Labels
?




The modified code, which works as per @S.Akbari's answer is to replace

List<Control> ControlsToCheck = GetAllLabelControls(dvPurchaseOrder).ToList();
foreach (Control c in ControlsToCheck)


with

foreach (Label lbl in GetAllLabelControls(dvPurchaseOrder).OfType<Label>().Cast<Label>())

Answer

Try this:

foreach (Label lbl in dvPurchaseOrder.Controls.OfType<Label>().Cast<Label>())
{
    lbl.Text = "";//Or other properties of the Label
}