如何从控件列表中获取标签文本

How to get Label text from a list of controls

我想遍历 ASP.Net DetailsView 中的所有控件并获取列表中的所有 Labels。然后我想对每个 Label 的文本做一些事情。我使用 this question 的第一个答案作为指导。它工作正常,但我无法访问 LabelsText 属性,因为我正在创建 Controls 的列表,而 Controls 不有一个 Text 属性。这是我的代码:

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;
        }
    }
}

在调试器中,我可以看到每个 ControlText,但是我的行

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

不会编译:

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.

顺便说一句,如果我使用上面提到的 link 中建议的确切语法,

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

我收到一条错误消息:

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

如何获得 LabelsText


按照@S.Akbari的回答工作的修改后的代码是替换

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

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

试试这个:

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