Search code examples
c#asp.netgridviewcode-behind

Accessing GridView Label field from Code-Behind


I have a gridview, and I'm trying to get the text value of a label in the textview where the code is:

<asp:TemplateField HeaderText="someText" SortExpression="someExpression">
    <ItemTemplate>
        <asp:Label ID="someLabel" runat="server" Text='<%# Bind("someField") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

I want to be able to get the text value of the "someLabel" from the selectedRow as a string in my codebehind.


Solution

  • Label someLabel = selectedRow.FindControl("someLabel") as Label;
    

    EDIT:

        private static Control FindControlRecursive(Control parent, string id)
        {
            if (parent.ID== id)
            {
                return parent;
            }
    
            return (from Control ctl in parent.Controls select FindControlRecursive(ctl, id))
                .FirstOrDefault(objCtl => objCtl != null);
        }
    

    and

    Label someLabel = FindControlRecursive(GridView.SelectedRow, "someLabel") as Label;
    

    EDIT 2:

    private void imageButton_Click(object sender, EventArgs e)
    {
         Label someLabel = (sender as Control).Parent.FindControl("someLabel") as Label;
    }