【问题标题】:How can I loop through Items in the Item Template from an asp:Repeater?如何从 asp:Repeater 循环遍历项目模板中的项目?
【发布时间】:2011-06-08 15:45:01
【问题描述】:

我有一个中继器,它与项目绑定在 preRender 上。在项目模板中,每一行都有一个复选框。这很好用。

我正在尝试在绑定项目模板后循环遍历项目模板中的所有复选框。有没有办法做到这一点?

【问题讨论】:

  • Repeater 上有很多生命周期事件可供您利用,包括在创建和/或绑定每个项目时发生的事件,您不必等到最后,您可以直接在 IDE 中自己发现这些事件。你需要用这些复选框做什么?
  • 为什么要在 preRender 上绑定Repeater?这很晚,通常您会在 Page_Load 阶段执行此操作。如果您只想在数据绑定上循环所有中继器行,中继器ItemDataBound-Event 将是一个好地方,因为这不会导致额外循环-
  • 在回发或客户端。任何一种都是可能的,但偏好对于获得可以使用的正确答案非常重要。
  • @Tim,PreRender 期间绑定的一个用例是您可能正在响应一个或多个其他事件。在这种情况下加载是不合适的,实际上其他事件处理程序可能不够用。

标签: c# asp.net repeater


【解决方案1】:

听起来你想使用 ItemDataBound 事件。

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

您需要检查RepeaterItem 的ItemType,这样您就不会尝试在Header/Footer/Seperator/Pager/Edit 中找到复选框

您的活动看起来类似于:

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;
    }
}

可以通过在后面的代码中添加事件来引发此事件,如下所示:

rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);

或者通过添加到客户端的控件中:

onitemdatabound="rptItems_ItemDataBound"

或者,您可以按照其他人的建议进行操作并遍历RepeaterItems,但是您仍然需要检查项目类型。

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;
    }
}

您可能想在 Page PreRender 中,在Repeater 被绑定之后这样做。

【讨论】:

  • 我在迭代方法中为 检查 itemtype 投票 +1
【解决方案2】:

试试这个。

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

    //do something with the checkbox
}

【讨论】:

    【解决方案3】:
    for (int item = 0; item < Repeater.Items.Count; item++)
    {
       CheckBox box = Repeater.Items[item].FindControl("CheckBoxID") as CheckBox;
       if (box.Checked)
       {
          DoStuff();
       }
       else
       {
          DoOtherStuff();
       }
    }
    

    【讨论】:

      【解决方案4】:

      我想到了一些不同的想法:

      1. 是否需要在 preRender 中绑定此中继器?考虑在 Page_Load 事件之后使用更典型的绑定方式。

      2. 为什么要在中继器绑定后查找复选框?你可以做任何你需要做的事情它被使用这个事件绑定:

        OnItemDataBound="Repeater1_OnItemDataBound"
        
      3. 无论哪种方式,您都可以随时返回并查看中继器的内部,只需遍历它即可。请注意,如果复选框嵌套在中继器项内的不同元素中,您可能需要进行递归搜索

        for each (RepeaterItem r in Repeater1.Items) {
            CheckBox c = r.FindControl("CheckBox1") as CheckBox;
            //DO whatever
        }
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-26
        • 1970-01-01
        • 1970-01-01
        • 2018-06-14
        • 2019-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多