动态链接按钮点击事件不工作
本文关键字:事件 工作 链接 按钮 动态 | 更新日期: 2023-09-27 18:12:30
我有以下代码,其中我填写数据库值的数据表3列。并添加1列名为ACTION,其中有动态生成的LINKBUTTONs。
但是当我点击这个按钮时,它的事件不会触发。
我调用fillConfGrid()函数后,每3秒
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());
}
}
这里的问题是按钮是动态生成的,因此Post-back不存在。你的选择是:
- 在OnInit方法中重新创建页面。
- 尝试使用Form集合来处理onClick事件