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.
RetrieveAccompanyListcan you do a .Sort on theRetrieveAccompanyList?RetrieveAccompanyListis just getting the value of my"gtpd_accompany01"session. I contains aList<Accompany>so I guess it was chronologically sorted. I debug my program and saw that the value inserted in thebtnRemoveAccompany.CommandArgumentis different in each iteration, but when the event access it, it is always the last value of the list.RetrieveAccompanyListis defines also if you are holding values in a List<Accompany> can you sort on that after the list is loadedList<T>.RemoveAll()returns the number of items that were removed, so you don't need the call toExists. Instead, useif (accompanies.RemoveAll(o => o.AccompanyID == accompanyID) != 0) { HttpContext.Current.Session["gtpd_accompany01"] = accompanies; this.PopulateAccompanyList(); }