I am having trouble adding a control programmatically in a Panel where the control has an event inside a loop. Here’s my code:
pnlAccompanies.Controls.Clear();
foreach (var accompany in this.RetrieveAccompanyList())
{
var btnRemoveAccompany = new LinkButton();
btnRemoveAccompany.CommandArgument = accompany.AccompanyID.ToString();
btnRemoveAccompany.CssClass = "close";
btnRemoveAccompany.Controls.Add(new Literal() { Text = "×" });
btnRemoveAccompany.Click += this.btnRemoveAccompany_Click;
smGTPForm.RegisterAsyncPostBackControl(btnRemoveAccompany);
pnlAccompanies.Controls.Add(btnRemoveAccompany);
}
And here’s my code of the event:
protected void btnRemoveAccompany_Click(object sender, EventArgs e)
{
var accompanyID = ((LinkButton)sender).CommandArgument.Parser<int>();
var accompanies = this.RetrieveAccompanyList();
if (accompanies.Exists(o => o.AccompanyID == accompanyID))
{
accompanies.RemoveAll(o => o.AccompanyID == accompanyID);
HttpContext.Current.Session["gtpd_accompany01"] = accompanies;
this.PopulateAccompanyList();
}
}
When I have 2 or more value in the accompanies, the return of the ((LinkButton)sender).CommandArgument is always the last one in the loop, even though I specifically put a different value in each iteration in the ((LinkButton)sender).CommandArgument. Why is it like this?
My code is in C# 4.0, ASP.NET, build in VS2010 Pro.
Please help. Thanks in advance.
You have not assigned the ID value for btnRemoveAccompany,so when you click on this button ,event doesn’t know which control raised this event,as all the controls have same attributes.try adding ID value for all the Controls.