How do I access a control in the HeaderTemplate of my GridView
Asked Answered
J

5

11

I want to have a DropDownList in the header of my GridView. In My codebehind I can't seem to access it. Here is the 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>

And here is the section in the code behind where I am trying to access the control '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();

}

You will notice that I am trying to use FindControl to get a reference to the DropDownList Control. This call returns null instead of returning the control. How do I get access to the control?

Jonme answered 5/3, 2009 at 18:24 Comment(0)
I
5

With Repeaters, you access headerTemplate items by using FindControl in the OnItemDataBoundEvent like this:

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

Does this work for GridViews as well?

Isocracy answered 13/3, 2009 at 18:54 Comment(0)
O
3
private void GetDropDownListControl()
    {
        DropDownList TypeFilter = ((DropDownList)this.yorGridView.HeaderRow.FindControl("TypeFilter"));
    }
Oversell answered 18/6, 2013 at 12:52 Comment(0)
M
2
protected void ObjectDataSource1__RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
             DropDownList typeFilter = (DropDownList)GridView1.FindControl("TypeFilter");
        }
     }
Matamoros answered 9/8, 2011 at 11:16 Comment(0)
R
1

Try this to find a control in the HeaderTemplate without a row-data-bind, if that's what is needed:

private void Lab_1_GV1_Populate_SearchText()
    {
        GridView GV1 = (GridView)FindControl("Lab_1_GV1");
        TextBox TXB1 = (TextBox)GV1.HeaderRow.FindControl("Lab_1_TX2GV1");
    }

Thanks

Ruchir

Roeser answered 23/8, 2013 at 10:19 Comment(0)
D
0
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
DropDownList ddlLocation = (DropDownList)e.Row.FindControl("ddlLocation");
ddlLocation.DataSource = dtLocation;
ddlLocation.DataBind();
}
}
}
Dilettante answered 22/5, 2012 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.