views:

80

answers:

1

Hello. At my user-control I populate listbox with collection and want save data in viewstate\controlstate for further autopostback using.

protected void btFind_Click(object sender, EventArgs e)
{
    var accounts = new AccountWrapper[2];
    accounts[0] = new AccountWrapper { Id = 1, Name = "1" };
    accounts[1] = new AccountWrapper { Id = 2, Name = "2" };

    lbUsers.DataSource = accounts;
    lbUsers.DataBind();
    ViewState["data"] = accounts;
} 

ListBox is populated at button click. When I save accounts to ViewState listBox is empty, when not it displays collection good. What's reasonn of this behaviour?

+1  A: 

After your button is being clicked, PostBack occurs and ListBox loses it's state.

void lbUsers_DataBinding(object sender, EventArgs e)
{
    if (this.IsPostBack &&)
    {
        AccountWrapper[] accounts = this.ViewState["data"] as AccountWrapper[];
        if (accounts!= null)
        {
            lbUsers.DataSource = accounts;
            lbUsers.DataBind();
        }
    }
}

(don't forget to subscribe to DataBinding event of your ListBox in markup)

Also I recommend you to encapsulate your access to ViewState:

private AccountWrapper[] Accounts
{
    get { return this.ViewState["data"] as AccountWrapper[]; }
    set { this.ViewState["data"] = value;
}
abatishchev
Why downvote..?
abatishchev
I know what you mean. I got two and no explaination!!!
Daniel Dyson