2014-01-05 38 views
0

我想最好創建一個自定義的控制是這樣的:標準子控件的自定義控件 - 爲什麼它們的ID爲null?

<foo:Frobnicate runat="server"> 
    <DoStuffWithThese> 
     <asp:TextBox runat="server" ID="fizzbot" /> 
    </DoStuffWithThese> 
    <!-- other controls can be in the wrapper but outside the DoSomeStuffWithThese collection -->  
    <asp:DropDownList runat="server" ID="othercontrol" /> 
</foo:Frobnicate> 

,但我會在必要時解決此:

<foo:Frobnicate runat="server"> 
    <DoStuffWithThese> 
     <asp:TextBox runat="server" ID="fizzbot" /> 
    </DoStuffWithThese> 
    <AndOtherStuffWithThese>  
     <asp:DropDownList runat="server" ID="othercontrol" /> 
    </AndOtherStuffWithThese> 
</foo:Frobnicate> 

我可以訪問控件的代碼隱藏OK(在第二,不理想的例子),但由於某些原因,他們的ID(我需要)是NULL

這裏是隱藏代碼:

[ParseChildren(true)] 
public class Frobnicate : WebControl { 

     [PersistenceMode(PersistenceMode.InnerProperty)] 
     public List<WebControl> DoStuffWithThese { get; set; } 

     [PersistenceMode(PersistenceMode.InnerProperty)] 
     public List<WebControl> AndOtherStuffWithThese { get; set; } 

     public override OnLoad(EventArgs e) { 
     base.OnLoad(e); 

     foreach(Control currentControl in DoStuffWithThese) { 
      // the control can be accessed (e.g. I can see it's a TextBox, etc. 
      // but currentControl.ID == null here -- why? :(
     } 

} 

有誰知道這是爲什麼?更重要的是,我如何解決這個問題,以便我可以使用這些格式之一獲得自定義控件,並且能夠訪問這些ID?

回答

0

你可以得到下拉的ID嗎?如果是這樣,我認爲它與缺少runat = server的其他項目有關。

+0

不,我可以既不得到下拉或文本框ID =無論是在自定義控件,我可以訪問它,但自定義控件的OnLoad ID爲空。將代碼示例更新爲包含容器中的runat服務器 – Whisker

+0

Hi Whisker:該代碼適用於我的目的。不知道爲什麼。我必須做出一些改變才能實現這一目標。只有第二個例子有效。 –

1

我相信你必須在你的類中實現INamingContainer,WebControl不會自己做到這一點。請注意,它只是一個標記界面,您不需要任何代碼。另外,您應該使用ITemplate(它允許您實際創建控件並在控件的輸出中使用它們)而不是控件列表。

這應該是有幫助的:http://msdn.microsoft.com/en-us/library/36574bf6(v=vs.85).aspx

如果這不是你想要的,請在你實際上試圖做的,爲什麼你不想使用模板詳細說明。

要解釋一點 - 只要添加到服務器控件的引用,您實際上並不增加,隨時隨地頁/控件樹,這意味着它是不是實際上創建的,它不」 t作爲頁面的一部分,真的(其中包括一個有用的UniqueID/ClientID,以及幾乎除構造函數外的任何邏輯)。

當您擁有該模板時,可以使用數據綁定來填寫所需的數據等,例如您可以使用FindControl訪問控件(或者只使用Controls集合,但請注意模板將會可能還包含文字和其他東西,而不僅僅是您的控件)。

相關問題