如何在转发器页眉或页脚中查找控件

mbi*_*ard 119 asp.net controls repeater findcontrol

我想知道如何在Asp.Net Repeater控件的HeaderTemplate或FooterTemplate中找到控件.

我可以在ItemDataBound事件上访问它们,但我想知道如何获取它们(例如,在页眉/页脚中检索输入的值).

注意:我在找到答案之后在这里发布了这个问题,以便我记住它(也许其他人可能会觉得这很有用).

mbi*_*ard 170

正如评论中所指出的,这仅适用于您使用DataBound转发器后.

要在标题中查找控件:

lblControl = repeater1.Controls[0].Controls[0].FindControl("lblControl");
Run Code Online (Sandbox Code Playgroud)

要在页脚中查找控件:

lblControl = repeater1.Controls[repeater1.Controls.Count - 1].Controls[0].FindControl("lblControl");
Run Code Online (Sandbox Code Playgroud)

用扩展方法

public static class RepeaterExtensionMethods
{
    public static Control FindControlInHeader(this Repeater repeater, string controlName)
    {
        return repeater.Controls[0].Controls[0].FindControl(controlName);
    }

    public static Control FindControlInFooter(this Repeater repeater, string controlName)
    {
        return repeater.Controls[repeater.Controls.Count - 1].Controls[0].FindControl(controlName);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这非常有效.只需一个注意事项 - 这只适用于您将中继器数据化后. (10认同)
  • 这个答案伤害了我的眼睛. (8认同)
  • 这是一种如此丑陋的方式......但它对我有用.非常感谢你!如果可能的话,我会给你超过+1. (2认同)

小智 50

好的解决方案

您可以在ItemCreated事件中检查项目类型:

protected void rptSummary_ItemCreated(Object sender, RepeaterItemEventArgs e) {
    if (e.Item.ItemType == ListItemType.Footer) {
        e.Item.FindControl(ctrl);
    }
    if (e.Item.ItemType == ListItemType.Header) {
        e.Item.FindControl(ctrl);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你特意说ItemDataBound,这是ItemCreated,upvote. (4认同)
  • 同意,更好的解决方案.只需保存对控件的引用. (3认同)
  • 我特意问过如何在不参加其中一项活动时获得它们. (2认同)

小智 5

您可以对ItemCreated事件的控件进行引用,然后再使用它.

  • 你只是问你以后如何访问它,pascal给出的答案是设置一个参考点,然后使用它是完全有效的. (12认同)