views:

82

answers:

2

I'm creating a composite control for a DropDownList (that also includes a Label).

The idea being that I can use my control like a dropdown list, but also have it toss a Label onto the page in front of the DDL.

I have this working perfectly for TextBoxes, but am struggling with the DDL because of the Collection (or Datasource) component to populate the DDL.

Basically I want to be able to do something like this:

<ecc:MyDropDownList ID="AnimalType" runat="server" LabelText="this is what will be in the label">
<asp:ListItem Text="dog" Value="dog" />
<asp:ListItem Text="cat" Value="cat" />
</ecc:MyDropDownList>

The problem is, I'm not extending the DropDownList class for my control, so I can't simply work it with that magic. I need some pointers to figure out how I can turn my control (MyDropDownList), which is currently just a System.Web.UI.UserControl, into something that will accept List items within the tag and ideally, I'd like to be able to plug it into a datasource (the same functions that the regular DDL offers).

I tried with no luck just extending the regular DDL, but couldn't get the Label component to fly with it.

A: 

The easiest thing would be to go back to your original option of extending the DropDownList control. What problems did you have getting the label to work with it? Those problems are probably easier to solve?

Ben Robinson
+1  A: 

after doing some digging and searching I found a solution that works.

Hopefully this will help someone else out in the future

[ParseChildren(true, "Items")]
public class EDropDownList : CompositeControl, IValidatedFields
{
    public string PromptingText { get; set; }
    public string Value { get; set; }
    public Label __Label { get; set; }
    private ListItemCollection _items;
    public DropDownList __DropDownList;
    public ListItemCollection Items 
    {
        get { return _items; }
        set
        {
            if (_items != value)
            {
                _items = value;
            }
        }
    }

    public string Type { get { return "DropDownList"; } }


    public EDropDownList()
    {
        __Label = new Label();
    }
    protected override void CreateChildControls()
    {
        __DropDownList = new DropDownList();
        foreach (ListItem myItem in _items)
        {
            __DropDownList.Items.Add(myItem);
        }
        Controls.AddAt(0, __Label);
        Controls.AddAt(1, __DropDownList);
    }

    protected override void OnLoad(EventArgs e)
    {
        // label section            
        __Label.Text = PromptingText+"<br />";
        __Label.ForeColor = Color.Red;
        __Label.Visible = false;
        // ddl section
        if (Page.IsPostBack)
            Value = __DropDownList.SelectedValue;
    }
}
Kyle