asp.netaspbutton

How to add onclick event of dynamically added buttons


How to add OnClick event of dynamically added buttons in asp.net. I have added buttons dynamically and now I want to create an clickevent for those buttons.

 if (dtTasks.Rows[j]["EmpID"].Equals(dtEmployees.Rows[i]["EmpID"]))
 {
       TableRow r = new TableRow();
       TableCell[] cells =  new TableCell();
       Button btn = new Button();
       btn.ID = "btn" + dtTasks.Rows[j]["TaskID"].ToString();
       btn.Text = "Add Comment";
       btn.OnClientClick = "Click";
       cells.Controls.Add(btn);
 }

Solution

  • You can add the button's Click handler like this.

     btn.Click += new EventHandler(btnClick);