【问题标题】:LinkButton.Click event not firing when dynamically attached in GridView row databound在 GridView 行数据绑定中动态附加时,LinkBut​​ton.Click 事件未触发
【发布时间】:2016-07-29 14:56:46
【问题描述】:

我在asp:UpdatePanel 中有一个asp:GridView,它有一列asp:LinkButton 控件。

在行数据绑定事件中,LinkBut​​ton 获取分配的点击事件处理程序。

我已经尝试了所有我能找到的方法来连接点击,甚至没有任何事件触发。

我做错了吗?

aspx:

<asp:UpdatePanel ID="MainUpdatePanel" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Label ID="lblTest" Text="test" runat="server" />
        <asp:GridView ID="gvClientsArchive" runat="server" AllowSorting="true" DataSourceID="dsClients" 
            OnRowDataBound="gvClientsArchive_RowDataBound" SkinID="gvList"
            AllowPaging="true" PageSize="25" Visible="false">
        ...

后面的代码:

protected void gvClientsArchive_RowDataBound(object sender, GridViewRowEventArgs e)
{
    ...
    int company_id = int.Parse(drvRow["company_id"].ToString());
    LinkButton lnkRestore = (LinkButton)e.Row.FindControl("lnkRestore");
    lnkRestore.Click += new System.EventHandler(this.doRestore);

按钮处理程序代码:

private void doRestore(object sender, EventArgs e)
{
    lblTest.Text = "restore clicked";
}

我也试过了:

protected void gvClientsArchive_RowDataBound(object sender, GridViewRowEventArgs e)
{
    ...
    LinkButton lnkRestore = (LinkButton)e.Row.FindControl("lnkRestore");
    lnkRestore.Click += delegate
    {
        lblTest.Text = "restore clicked";
    };

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    RowDataBound 如果你想注册事件处理程序是不合适的。使用RowCreated

    protected void gvClientsArchive_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType ==  DataControlRowType.DataRow)
        {
            LinkButton lnkRestore = (LinkButton)e.Row.FindControl("lnkRestore");
            lnkRestore.Click += new System.EventHandler(this.doRestore);
        }
    }
    

    RowDataBound 仅在您对网格进行数据绑定而不是在需要的每个回发时触发,因为所有控件都在页面生命周期结束时处理。也太晚了。

    如果您使用TemplateFields,则更容易在 aspx 上以声明方式注册处理程序。

    【讨论】:

    • 我现在会尝试实现它。为什么不合适?
    • Tim 我使用TemplateField 作为LinkButton 行的列。我可以看到如何在 aspx 中添加 OnClick,但是如何在 click 处理程序事件中获取其余数据行的上下文?
    • @JamesWierzba:您必须将Sender 转换为LinkButton(或Control),然后将NamingContainer 转换为GridViewRow。现在您可以使用row.FindControl 查找此行中的所有其他控件。
    • 谷歌搜索 1 天后你救了我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2011-01-22
    相关资源
    最近更新 更多