Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through Items in the Item Template from an asp:Repeater?

I have a repeater, which is bound on preRender with items. In the Item template each row has a check box. This works fine.

I'm trying to loop through all the checkboxes in the item template after it has been bound. Is there any way of doing this?

like image 963
Funky Avatar asked Jun 08 '11 15:06

Funky


People also ask

How many pre defined templates in repeater control?

Repeater has 5 inline template to format it: <FooterTemplate> <ItemTemplate> <AlternatingItemTemplate> <SeperatorTemplate>

How many inline templates are used in repeater control?

A Repeater has five inline templates to format it: <Itemtemplate> - It defines how the each item is rendered from the Data Source collection.


1 Answers

It sounds to me like you want to use the ItemDataBound event.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx

You will want to check the ItemType of the RepeaterItem so that you don't attempt to find the checkbox in Header/Footer/Seperator/Pager/Edit

Your event would look something along the lines of:

void rptItems_ItemDataBound(object sender, RepeaterItemEventArgs e) {     if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)     {         var checkBox = (CheckBox) e.Item.FindControl("ckbActive");          //Do something with your checkbox...         checkBox.Checked = true;     } } 

This event can be raised by adding the event in your code behind like so:

rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound); 

Or by adding it to the control on the client:

onitemdatabound="rptItems_ItemDataBound" 

Alternatively you can do as the others suggested and iterate over the RepeaterItems, however you still need to check the itemtype.

foreach (RepeaterItem item in rptItems.Items) {     if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)     {         var checkBox = (CheckBox)item.FindControl("ckbActive");          //Do something with your checkbox...         checkBox.Checked = true;     } } 

You would want to do that in the Page PreRender, after the Repeater has been bound.

like image 133
Phill Avatar answered Oct 02 '22 22:10

Phill