无法在转发器项目中找到控制权

时间:2013-04-24 14:41:10

标签: asp.net repeater

我正在使用转发器:

<asp:Repeater ID="rptCategories" runat="server" OnItemDataBound="RptCategories_ItemDataBound">
            <ItemTemplate>
                <asp:Panel CssClass="category-wrapper" ID="pnlCategory" runat="server">
                    <%# Eval("SponsorshipCategoryName") %>
                    <asp:HiddenField runat="server" ID="hdnCategoryID" Value='<%# Eval("SponsorshipCategoryID") %>' />
                </asp:Panel>
            </ItemTemplate>
        </asp:Repeater>

取决于我的类别类型,我在我的代码后面的面板中添加了RadionButtonList或复选框列表。

我设置了id:

rblItems.ID = "rbl_" + category.SponsorshipCategoryID;

然后将控件放在panel

panel.Controls.Add(rblItems);

现在我已经能够遍历所有类别面板并获得那些单选按钮列表或复选框。

为此我循环rptCategories.Items

  foreach (RepeaterItem rptItem in rptCategories.Items)
           {
               var hdnCategoryID = rptItem.FindControl(HdnCategoryID_ID) as 
                  HiddenField;
               var pnlCategory = rptItem.FindControl(PnlCategory_ID) as Panel;
               var categoryID = (hdnCategoryID == null || hdnCategoryID.Value == 
               string.Empty) ? 0 : int.Parse(hdnCategoryID.Value);
           }

它找到隐藏的字段和面板就好了。但是当我试图在我的面板中找到带有ID的控件时,我感兴趣的是它返回null。

var control = pnlCategory.FindControl("rbl_" + categoryToUpdate.SponsorshipCategoryID);

我不能在这里使用item数据绑定事件。任何想法可以是什么问题?

1 个答案:

答案 0 :(得分:2)

它可能是两个问题之一(或两者兼而有之):

  1. 您正在动态添加控件:panel.Controls.Add(rblItems)。为了能够检索这些动态添加的控件,必须在每个Postback上重新添加 。恕我直言,添加动态添加控件的最佳位置是OnInit()事件。

  2. 正如@skhurams所说:动态添加的控件的ID可能存在问题。虽然您明确设置了每个控件的ID,但Repeater会自动更改这些ID以确保在特定页面上不重复ID。查看是否是这种情况的最佳方法是查看生成的网页的来源。检查ID是否与您的预期不同。您可以选择将ClientIDMode设置为“静态”,但请确保每个ID都是真正唯一的。