Recently I had the need to loop through a collection of repeaters on a page within a website I was working on. Here was the situation, we had two repeaters on an ASP page that displayed items that were owned by you in one and ones that had been shared with you in another. Before rendering the repeaters to the page we needed to determine which repeater item in either of the repeaters was currently selected so that we could set the style of the repeater item to highlight it.
I was struggling with how exactly to go about looping through both item collections without having to duplicate the same piece of functionality. My original idea was to create a for each loop that went through both repeaters item collections, but in C# .NET it is not possible to have a single for each loop go through multiple parent objects. The thing you can do though is have a for each loop within a for each loop, so I thought maybe I should go through all the controls on the page till I find the repeaters and then loop through them otherwise skip to the next item. That would have worked sure, but it would have been very intensive as far as processing power is concerned.
Then it hit me, why not put the item collections into their own collection? So I created a generic list of type RepeaterItemCollection and added each repeater’s item collections to it and then looped through the generic list and through each item in the individual repeater. This worked great for me, I put this simple functionality in the pre-render event and it goes through all the items in the repeaters and selects the one that is currently selected. This may not be the most elegant or simplest resolution to the problem that I was having, but it was the simplest I could come up with and it made me feel stupid for how much time I had spent coming up with it because it seemed so simple.
Below you will find the code that I used, cleaned up for clarity. If you know of a better way to do this or if it helped you please let me know via the comment section below.
List<RepeaterItemCollection> rptItemCollection = new List<RepeaterItemCollection>();
rptItemCollection.Add(Repeater1.Items);
rptItemCollection.Add(Repeater2.Items);
foreach (RepeaterItemCollection Items in rptItemCollection)
{
foreach (RepeaterItem item in Items)
{
if (item.Controls.Count >= 0)
{
Panel pnlBackground = null;
HiddenField hdItemKey = null;
foreach (Control ctl in item.Controls)
{
if (ctl.GetType() == typeof(Panel))
{
pnlBackground = (Panel)ctl;
foreach (Control child in pnlBackground.Controls)
{
if (child.GetType() == typeof(HiddenField))
{
if (((HiddenField)child).ID == "hdItemKey")
{
hdItemKey = (HiddenField)child;
}
}
}
}
}
if (pnlBackground != null && hdItemKey != null)
{
if (hdItemKey.Value == hdSelectedKey.Value)
{
pnlBackground.BackColor = System.Drawing.Color.FromName("#FFFFC0");
pnlBackground.BorderColor = System.Drawing.Color.FromName("#FFFFC0");
}
}
}
}
}

Recent Comments