从Code-Behind访问GridView标签字段

时间:2011-06-17 19:16:11

标签: c# asp.net gridview code-behind

我有一个gridview,我正在尝试在textview中获取标签的文本值,代码为:

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

我希望能够在我的代码隐藏中将selectedRow的“someLabel”的文本值作为字符串获取。

1 个答案:

答案 0 :(得分:1)

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

编辑:

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

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

编辑2:

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