将UserControl的数据保存到ViewState

时间:2010-08-05 08:27:11

标签: c# asp.net user-controls viewstate

在我的用户控件中,我使用集合填充列表框,并希望在viewstate \ controlstate中保存数据,以便进一步使用自动回复。

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。当我将帐户保存到ViewState时,listBox为空,否则显示集合好。这种行为的原因是什么?

1 个答案:

答案 0 :(得分:2)

单击按钮后,会发生PostBack,ListBox会丢失它的状态。

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();
        }
    }
}

(不要忘记在标记中订阅ListBox的DataBinding事件)

另外,我建议您封装对ViewState的访问权限:

private AccountWrapper[] Accounts
{
    get { return this.ViewState["data"] as AccountWrapper[]; }
    set { this.ViewState["data"] = value;
}