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

好久不见. 提交于 2019-11-30 06:08:10

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.

CYMR0

Try this.

for each (RepeaterItem ri in Repeater1.Items)
{
     CheckBox CheckBoxInRepeater = ri.FindControl("CheckBox1") as CheckBox;

    //do something with the checkbox
}
for (int item = 0; item < Repeater.Items.Count; item++)
{
   CheckBox box = Repeater.Items[item].FindControl("CheckBoxID") as CheckBox;
   if (box.Checked)
   {
      DoStuff();
   }
   else
   {
      DoOtherStuff();
   }
}
spiderman

A few different thoughts come to mind:

  1. Is there a specific need to bind this repeater in preRender? Consider using the more typical way of binding after Page_Load event.

  2. Why are you wanting to look for the checkboxes after the repeater has been bound? Can you do whatever you need to do while it is being bound by using this event:

    OnItemDataBound="Repeater1_OnItemDataBound"
    
  3. Either way, you can always go back and look inside the repeater by just iterating through it. Note that you might have to do a recursive search if the checkbox is nested in a different element inside the repeater item

    for each (RepeaterItem r in Repeater1.Items) {
        CheckBox c = r.FindControl("CheckBox1") as CheckBox;
        //DO whatever
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!