2014-01-05 35 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集合,但请注意模板将会可能还包含文字和其他东西,而不仅仅是您的控件)。

相关问题