ASP.NET Repeater - 循环项目模板中的项目

Fun*_*nky 33 c# asp.net repeater

我有一个转发器,它与preRender绑定了项目.在Item模板中,每行都有一个复选框.这很好用.

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

谢谢!

Phi*_*ill 44

听起来我想要使用ItemDataBound事件.

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

您将需要检查RepeaterItem的ItemType,以便您不会尝试在页眉/页脚/分隔符/寻呼机/编辑中找到该复选框

您的活动看起来像是:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);
Run Code Online (Sandbox Code Playgroud)

或者将其添加到客户端上的控件:

onitemdatabound="rptItems_ItemDataBound"
Run Code Online (Sandbox Code Playgroud)

或者,您可以像其他人建议的那样执行并迭代RepeaterItems,但是您仍然需要检查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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在转发器绑定后,您可能希望在Page PreRender中执行此操作.


小智 16

试试这个.

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

    //do something with the checkbox
}
Run Code Online (Sandbox Code Playgroud)