c# - 如何访问我的 GridView 的 HeaderTemplate 中的控件

标签 c# asp.net findcontrol

我想在我的 GridView 的标题中有一个 DropDownList。在我的代码隐藏中,我似乎无法访问它。这是 HeaderTemplate:

<asp:TemplateField SortExpression="EXCEPTION_TYPE">
    <HeaderTemplate>
        <asp:Label ID="TypeId" runat="server" Text="Type" ></asp:Label>
        <asp:DropDownList ID="TypeFilter" runat="server" AutoPostBack="true">
        </asp:DropDownList>
    </HeaderTemplate>
    ...
</asp:TemplateField>

这是我试图访问控件“TypeFilter”的代码后面的部分。

protected void ObjectDataSource1_Selected(object sender, 
                                          ObjectDataSourceStatusEventArgs e)
{
    DataTable dt = (DataTable)e.ReturnValue;
    int NumberOfRows = dt.Rows.Count;
    TotalCount.Text = NumberOfRows.ToString();
    DataView dv = new DataView(dt);
    DataTable types = dv.ToTable(true, new string[] { "EXCEPTION_TYPE" });
    DropDownList typeFilter = (DropDownList)GridView1.FindControl("TypeFilter");
    typeFilter.DataSource = types;
    typeFilter.DataBind();

}

您会注意到我正在尝试使用 FindControl 来获取对 DropDownList 控件的引用。此调用返回 null 而不是返回控件。我如何获得对控件的访问权限?

最佳答案

使用 Repeater,您可以像这样在 OnItemDataBoundEvent 中使用 FindControl 来访问 headerTemplate 项:

RepeaterItem item = (RepeaterItem)e.Item;
if (item.ItemType == ListItemType.Header) {
    item.FindControl("control"); //goes here
}

这也适用于 GridView 吗?

关于c# - 如何访问我的 GridView 的 HeaderTemplate 中的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/615950/

相关文章:

asp.net - HTTP 模块拦截请求并中断自定义错误配置

c# - 用户单击行链接按钮控件时如何获取中继器的项目行ID

c# - WebClient多线程响应

c# - 在 ASP.NET 中将 html 导出为 pdf

c# - 如何在某些情况下从数据表中选择全部?

c# - FindControl - 找不到下拉列表

c# - RowDataBound-Event 中的 FindControl 以错误结束

c# - 为什么要使用 Windows.Forms.Timer?

c# - 将整数列表从 C# 传递到 Oracle 存储过程

c# - 捕捉 IP 地址变化