views:

358

answers:

1

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

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.

Bryan
I don't think that's it (though I will double-check this later when I get a chance), because I can create a DropDownList on a plain ASPX page (not part of a control), and re-initialise its Items collection and set a default value in Page.OnInit on every page load and in this case it correctly restores the posted value between OnInit and OnLoad.
Quick Joe Smith
I'd guess this might be down to viewstate, to be honest. If you're still struggling with this and Bryan's solution doesn't help, the answer I just posted to another question might help: http://stackoverflow.com/questions/3854193/3865762#3865762
Owen Blacker