views:

134

answers:

1

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!

+2  A: 

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);
      }
   }
womp
Nice. Never seen this before.
Bryan
Awesome, thanks! I had to make a couple modifications, but your basic idea worked like a charm.
Spencer