动态链接按钮单击事件不起作用

时间:2014-07-10 11:33:02

标签: c# asp.net gridview click

我有以下代码,其中我按数据库值填充数据表3列。并添加另外一个名为ACTION的列,其中包含动态生成的LINKBUTTON。
但是当我点击这个按钮时,它的事件不会触发
我每隔3秒就调用一次fillConfGrid()函数

private void fillConfGrid()
{
    try
    {
        DataTable table = new DataTable();
        DataBase m_Connection = new DataBase();
        m_Connection.OpenDB("Database");
        string strTemp = "select col1,col2,col3 from Table1";
        OdbcCommand cmdSelect = new OdbcCommand(strTemp, m_Connection.oCon);
        OdbcDataAdapter da = new OdbcDataAdapter(cmdSelect);
        DataSet ds = new DataSet();
        da.Fill(ds);
        table = ds.Tables[0];
        table.Columns.Add("Action", typeof(string));

        confGrid.DataSource = table;
        confGrid.DataBind();
        //LinkButton lbl=null;
        for (int i = 0; i < confGrid.Rows.Count; i++)
        {
            LinkButton lbl = new LinkButton();
            lbl.ID = confGrid.Rows[i].Cells[0].Text;
            lbl.CommandArgument = confGrid.Rows[i].Cells[0].Text.Trim() + "," + confGrid.Rows[i].Cells[1].Text.Trim();
            lbl.Text = "Disconnect";
            lbl.Click += new EventHandler(lbl_Click);
            lblConfError.Text = confGrid.Rows[i].Cells[0].Text.Trim() + "," + confGrid.Rows[i].Cells[1].Text.Trim();
            confGrid.Rows[i].Cells[3].Controls.Add(lbl);                
        }

        m_Connection.CloseDB();
    }
    catch (Exception ex)
    {
        Response.Write("<script>alert('error 1: " + ex.Message.ToString() + "');</script>");
    }
}


protected void lbl_Click(object sender, EventArgs e)
{        
    lblConfError.Text = "Click event";
    CtiWS CtiWS1 = new CtiWS();
    LinkButton button = (LinkButton)sender;
    GridViewRow row = (GridViewRow)button.NamingContainer;
    if (row != null)
    {
        lblConfError.Text = "Click event";
        string cmdArgs = ((LinkButton)sender).CommandArgument.ToString();
        Response.Write("<script>alert('Argument : " + cmdArgs + "');</script>");
        string[] confParts = cmdArgs.Split(',');
        lblConfError.Text = confParts[0] + " : " + confParts[1];
        CtiWS1.SendCode("", "", "K:" + confParts[0] + ":" + confParts[1], HttpContext.Current.Session["HOSTID"].ToString());
    }        
}

1 个答案:

答案 0 :(得分:-1)

你在这里遇到的问题是动态生成的按钮WAS等等不存在。您的选择是:

  1. 在OnInit方法中重新创建页面。
  2. 尝试使用Form集合处理onClick事件。
相关问题