开发者

Can I populate list items in a ASP.NET dropdown list from a ASP.NET Placeholder?

I'm designing my own custom control that contains a .NET dropdownlist. What I'm wondering is if it is possible to populate my dropdownlist with listitems placed in a placeholder?

For example:

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

This doesn't work because the DropDownList control only allows ListItems as child controls. But, I want to do 开发者_如何学运维something similar to this so when the user includes my control on a page, they can do something like this:

<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>

Any suggestions or ideas? I know I can do this by dynamically adding the ListItems in the page code behind, but I'd like to avoid that if possible. Thanks!


One approach to this would be to give your control a [ParseChildren(true, "ListItemTemplate")] attribute.

If you then had a property called "ListItemTemplate", which was an array of ListItems, your markup would be parsed into that property. At runtime in your control, you could simply hand your dropdownlist the contents of that property.

Some non-tested example code:

   [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);
      }
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜