Monday, April 25, 2011

Registering Events and creating controls dynamically in ASP.NET


Hi fellows,
  yesterday I spend 4 hours straight, trying to register a simple click event of a series of dynamically created LinkButtons using ASP.NET (C#), I was unable to do that, as the event was not triggering, I was creating the instances of the Linkbutton every time the pageload event was called but all in vain.
I was trying to do something like this:
foreach (DataRow ddrList in dsCouseList.Tables[0].Rows)
trow = new TableRow();
tcell = new TableCell();
LinkButton btnremove = new LinkButton() { ID = ddrList["linkfield"].ToString(), Text = "Remove" };
btnremove.Click += new EventHandler(btnremove_Click);
tcell = new TableCell();
tcell.Controls.Add(new Label { Text = ddrList["buyerdescription"].ToString(), ID="descr" });
The thing I just missed and got stuck was when I assigned an ID (ID="descr") to the above label explicitly”.
What happened is that in case of more than one Data Rows in the Dataset dsCourseList,Tables[0].Rows, Labels with duplicate ID’s generated, in result restraining the click event to work properly.
I learned my lesson and wanted to share it with you all. 
So be careful with such pitfalls in programming and in real life too Smile
Happy development Smile