【问题标题】:Can I populate list items in a ASP.NET dropdown list from a ASP.NET Placeholder?我可以从 ASP.NET 占位符填充 ASP.NET 下拉列表中的列表项吗?
【发布时间】:2011-01-20 17:13:49
【问题描述】:

我正在设计我自己的包含 .NET 下拉列表的自定义控件。我想知道是否可以用放置在占位符中的列表项填充我的下拉列表?

例如:

<asp:DropDownList ID="ddlFilter" runat="server" >
  <asp:PlaceHolder ID="ListItemPlaceholder" runat="server"/>
</asp:DropDownList>

这不起作用,因为 DropDownList 控件只允许 ListItems 作为子控件。但是,我想做类似的事情,所以当用户在页面上包含我的控件时,他们可以做这样的事情:

<mytag:MyControl Mode="DropDown" runat="server">
    <ListItemTemplate>
        <asp:ListItem Text="C" Value="c"></asp:ListItem>
        <asp:ListItem Text="E" Value="e"></asp:ListItem>
        <asp:ListItem Text="B" Value="b"></asp:ListItem>
    </ListItemTemplate>
</myTag:MyControl>

有什么建议或想法吗?我知道我可以通过在后面的页面代码中动态添加 ListItems 来做到这一点,但如果可能的话,我想避免这种情况。谢谢!

【问题讨论】:

    标签: asp.net templates drop-down-menu placeholder


    【解决方案1】:

    解决此问题的一种方法是为您的控件提供[ParseChildren(true, "ListItemTemplate")] attribute.

    如果您有一个名为“ListItemTemplate”的属性,它是ListItems 的数组,您的标记将被解析为该属性。在您的控件中运行时,您可以简单地将下拉列表交给该属性的内容。

    一些未经测试的示例代码:

       [ParseChildren(true, "ListItemTemplate")]
       public class MyControl: Control
       {  
          private ArrayList employees = new ArrayList();
          private DropDownList myDropDownList = new DropDownList();
    
          public ArrayList ListItemTemplate
          {
             get 
             {
                return employees;
             }
          }
    
          protected override void CreateChildControls()
          { 
             myDropDownList.Items.AddRange(ListItemTemplate):
             Controls.Add(myDropDownList);
          }
       }
    

    【讨论】:

    • 不错。以前从未见过。
    • 太棒了,谢谢!我不得不做一些修改,但你的基本想法就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多