I am having a problem with dynamic link buttons which I need help with. I am creating a dynamic asp.net table based on records in a datatable. I am also using dynamic linkbuttons.
protected System.Web.UI.WebControls.LinkButton lb;
protected override void OnInit(EventArgs e)
{
// Build controls before page load
lb = new LinkButton();
lb.Text = "Update Image";
// LinkButton obj for updating record
lb.ID = "UpdateImg";
lb.Click += new EventHandler(UpdateImg);
this.Controls.Add(lb);
base.OnInit(e);
}
I create a new linkbutton instance OnInit so I can add it to the page before page load.
foreach (DataRow r in tb.Rows) // Create new row foreach row in table
{
TableRow tr = new TableRow();
// Build cells
TableCell c1 = new TableCell();
TableCell c2 = new TableCell();
TableCell c3 = new TableCell();
TableCell c4 = new TableCell();
TableCell c5 = new TableCell();
TableCell c6 = new TableCell();
c1.Controls.Add(new LiteralControl(r["Image_id"].ToString()));
tr.Cells.Add(c1);
c2.Controls.Add(new LiteralControl(r["Image_name"].ToString()));
tr.Cells.Add(c2);
c3.Controls.Add(new LiteralControl(r["Alt_text"].ToString()));
tr.Cells.Add(c3);
c4.Controls.Add(new LiteralControl("<input id=\"" + r["Image_id"].ToString() + "\" type=\"checkbox\"" + "\"></input>"));
tr.Cells.Add(c4);
LinkButton lbcopy = new LinkButton();
lbcopy = lb;
lbcopy.ID = "UpdateImg" + i;
i++;
c5.Controls.Add(lbcopy);
tr.Cells.Add(c5);
c6.Controls.Add(new LiteralControl("<a href=\"javascript:void(0);\" onclick=\"DeleteImage('" + r["Image_id"].ToString() + "','" + r["Image_name"].ToString() + "');\"><img src=\"../images/clipboard/del.png\" id=\"" + r["Image_id"].ToString() + "\" width=\"20\" height=\"20\" BORDER=0></a>"));
tr.Cells.Add(c6);
tblImageLibrary.Rows.Add(tr); // Assign tr to table
I then use a foreach loop to iterate through each row in the datatable so I can build each table row and add the cells to each row. The problem I am having is the linkbutton appears in the very last row. Possibly because there is only one linkbutton object and through each loop iteration its being moved to the next row?
I am new to asp.net so go easy on me.