簡體   English   中英

無法通過FormView中的FindControl訪問CheckListBox

[英]Can't Access CheckListBox by FindControl in 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()事件中找到它,但是在ChangesMode和changedMode上找不到它,並且引用為null。

實際上,我想綁定ItemTemplate中的bulletList和EditTemplate中的CheckBoxList。

僅當控件直接包含在指定的容器中時, 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;
}

FormView上的FindControl僅適用於FormView的“ CurrentMode”屬性設置為的模板。

在您的情況下,如果將FormView設置為只讀模式,則只能對“ BulletedList”執行FindControl。因為這是控件所在的模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM