无法通过FormView中的FindControl访问CheckListBox

时间:2013-12-18 13:30:15

标签: c# asp.net formview

我有这样的表单视图和formview_databound()方法:

 <asp:FormView ID="frm" runat="server" DataKeyNames="Id" DataSourceID="dsSelectedProduct">
      <ItemTemplate>
           <asp:BulletedList ID="blstCatlist"  DataTextField="Name"  DataValueField="Id" runat="server"></asp:BulletedList>
     </itemTemplate>
 </asp:FormView>

if (frm.CurrentMode == FormViewMode.ReadOnl
{
   var blstCatlist = frm.FindControl("blstCatlist") as BulletedList;
}

blsCatlistnull。 我真的很困惑!因为可以 formview_Inserting()事件中找到它,但是在ChangingMode和changedMode上找不到它,引用为null。

实际上我想绑定ItemTemplate中的bulletList和EditTemplate中的CheckBoxList。

1 个答案:

答案 0 :(得分:0)

仅当控件直接包含在指定容器中时,

FindControl才会找到控件;该方法不会在控件内的控件层次结构中进行搜索。

要在您不知道其直接容器时找到控件,您需要一个自定义方法来搜索控件层次结构中的控件。

public static Control FindControlRecursive(Control rootControl, string controlID)
{
    if (rootControl.ID == controlID) return rootControl;

    foreach (Control controlToSearch in rootControl.Controls)
    {
        Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
        if (controlToReturn != null) return controlToReturn;
    }
    return null;
}
FindControl上的

FormView仅适用于FormView的“CurrentMode”属性设置为的模板。

在您的情况下,如果您的FormView设置为只读模式,则只能为“BulletedList”执行FindControl。因为这是您的控件所在的模板。

相关问题