Jordan Foreman
Jordan Foreman

Reputation: 3888

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.

Upvotes: 2

Views: 3799

Answers (1)

Bala R
Bala R

Reputation: 108937

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;
}

Upvotes: 1

Related Questions