DropDownList within composite control is losing selected value on postback

2.7k Views Asked by At

I am building a composite server control that currently only has a TextBox and a DropDownList. Here is the code in all its foetal glory:

public Address : CompositeControl
{
    private string[] _states = new string[]
    {
        string.Empty, "ACT", "NSW", "VIC", "QLD", "SA", "WA", "NT", "TAS"
    };
    private TextBox _street;
    private DropDownList _state;

    public string Street
    {
        get { return _street.Text; }
        set { _street.Text = value; }
    }
    public string State
    {
        get { return _state.Text; }
        set { _state.Text = value; }
    }

    public Address() : base()
    {
        EnsureChildControls();
    }

    protected override void CreateChildControls()
    {
        _street = new TextBox();
        _state = new DropDownList();

        _state.Items.AddRange(
            Array.ConvertAll<string, ListItem>(_states, ListItem.FromString));

        Controls.Add(_street);
        Controls.Add(_state);
    }
}

The control appears to work correctly across postbacks, that is until declarative values are set, e.g.:

<squee:Address runat="server" ID="a" Street="123 Fake St" State="VIC" />

After this, the text box continues to work correctly, but the _state member does not pick up the posted back values and instead just sticks to the declared value. I've checked the raw posted values in the Request object, and the new value for the list's UniqueID is there, but _state doesn't pick it up.

I'm pretty sure this is going to be something obvious, but I am just spinning my wheels here.

1

There are 1 best solutions below

3
On

This is happening because you are adding the ListItems on every page load. Don't recreate the list items on a PostBack, the ViewState will restore them.