【问题标题】:Accessing GridView Label field from Code-Behind从代码隐藏访问 GridView 标签字段
【发布时间】:2011-09-17 10:55:47
【问题描述】:

我有一个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”的文本值作为我的代码隐藏中的字符串。

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

    • 这是我一直在尝试的:Label tempLabel = GridView.SelectedRow.FindControl("someLabel") as Label;,但由于某种原因,这不起作用。知道为什么吗?
    • @Jordan 还有? tempLabel 为空?
    • 我得到一个空引用异常
    • 我遇到了parent.Name 的问题我正在使用 System.Web.UI.Control
    • @Jordan 哎呀~应该是parent.ID。我从我的 winforms 项目中复制了那个 sn-p。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多