Question

I have gridview, I want to do a foreach on it's rows and get the value from column's header where there's a Label for one cell from this row.

foreach (GridViewRow mainRow in grid1.Rows)
{
    var header = mainRow.Cells[2].Parent.FindControl("LabelID");//is null
}

How do I find it ?

Was it helpful?

Solution

If you want the value in RowDataBound event then you can check RowType like this

if(e.Row.RowType == DataControlRowType.Header)
{
    Label header = (Label)e.Row.FindControl("LabelID");
}

OTHER TIPS

I would access the headerRow and enumerate through the according cells (on buttonClick or on RowDataBound ...)

default.aspx

<asp:GridView AutoGenerateColumns="false" ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:Label ID="headerLabel1" runat="server" Text="Headercolumn1"></asp:Label>
            </HeaderTemplate>
            <ItemTemplate>
                <asp:Label ID="itemLabel1" runat="server" Text='<%# Eval("name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="btnGetHeader" runat="server" Text="GetHeader" OnClick="btnGetHeader_Click" />

default.aspx.cs

protected void btnGetHeader_Click(object sender, EventArgs e)
{
    foreach (TableCell headerCell in GridView1.HeaderRow.Cells)
    {
        // or access Controls with index 
        //     headerCell.Controls[INDEX]
        Label lblHeader = headerCell.FindControl("headerLabel1") as Label;
        if (lblHeader != null)
            Debug.WriteLine("lblHeader: " + lblHeader.Text);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top