【问题标题】:Event handler not firing on dynamic button click事件处理程序未在动态按钮单击时触发
【发布时间】:2014-04-07 18:21:59
【问题描述】:

我有一个带有 onclick 事件处理程序的动态创建按钮。问题是当我单击按钮时,它不会在代码隐藏中触发事件。

protected void gvOrder_RowDataBound(object sender, GridViewRowEventArgs e)
{
    DataTable dt = ds.Tables[0];
    DropDownList ddl = new DropDownList();
    TextBox txt = new TextBox();
    int index = 1;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ddl = e.Row.FindControl("ddlNewO") as DropDownList;
        txt = e.Row.FindControl("txtNewT") as TextBox;
    }
    foreach (DataRow r in dt.Rows)
    {
        string listitem = Convert.ToString(index);
        ddl.Items.Add(listitem);
        index++;
    }
    ddl.SelectedIndex = e.Row.RowIndex;
    if (e.Row.RowIndex == 0)
    {
        ddl.Enabled = false;
        txt.Enabled = false;
    }
    else if (e.Row.RowIndex != 0)
    {
        ddl.Items.Remove("1");
        //Create ED button


        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button btnED = new Button();
            btnED.ID = "btnED";
            btnED.CssClass = "buttonsmall";
            //btnED.CommandName = "ED";
            btnED.EnableViewState = true;
            btnED.Click += new EventHandler(btnED_Click);
            foreach (DataRow r in dt.Rows)
            {
                btnED.Attributes.Add("ID", r.ItemArray[2].ToString());
            if (r.ItemArray[3].ToString() == "1")
            {
                btnED.Text = "Disable";
            }
            else 
            {
                btnED.Text = "Enable";
            }
            //Add button to grid
            e.Row.Cells[5].Controls.Add(btnED); 
            }   
        }


    }

}
protected void btnED_Click(object sender, EventArgs e)
{
    // Coding to click event
}

【问题讨论】:

  • 你要创建多少个按钮?
  • 你有没有调试过代码,看看它正在点击 btnED.Click += new EventHandler(btnED_Click);
  • 能贴出gridview数据绑定代码吗?

标签: c# asp.net gridview webforms


【解决方案1】:

所以这里的问题是,当页面在回发时重新创建时 - 没有更多按钮!需要在每个回帖的页面上添加动态控件以正确触发事件。但是,在您的情况下,当GridView 绑定时第一次加载时,您将按钮添加到页面。但是在点击后返回的帖子上没有再次添加按钮,因为 GridView 没有再次绑定数据。因此 ASP.NET 无法派生事件的来源,并对其进行抑制。

这里的修复是将 GridView 与每个回发的数据绑定。从字面上看,如果你有if (!IsPostBack) - 删除它。或者您可以在模板字段中添加按钮并使用可见性 - 也可能是一种方法。

【讨论】:

  • 感谢您的回答。如果您认为我的问题有效,我将不胜感激。
【解决方案2】:

您需要在创建的行上添加一个点击处理程序,而不是在我相信的数据绑定上。

protected void gvOrderRowCreated(object sender, GridViewRowEventArgs e)
{
    switch (e.Row.RowType) {
        case DataControlRowType.DataRow:
            Button btn = (Button)e.Row.FindControl("btnED");
            btn.Command += btnED_Click;
            break;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    相关资源
    最近更新 更多