C# 将UserControl的数据保存到ViewState
在我的用户控件中,我用集合填充列表框,并希望将数据保存在viewstate\controlstate中,以便进一步使用自动回发C# 将UserControl的数据保存到ViewState,c#,asp.net,user-controls,viewstate,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 Acc
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;
}
单击按钮时填充列表框。当我将帐户保存到ViewState时,列表框为空,否则显示collection good。这种行为的原因是什么?单击按钮后,会发生回发,列表框将失去其状态
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();
}
}
}
(别忘了订阅标记中列表框的数据绑定事件)
我还建议您封装对ViewState
的访问:
private AccountWrapper[] Accounts
{
get { return this.ViewState["data"] as AccountWrapper[]; }
set { this.ViewState["data"] = value;
}
没有人。非常感谢。我的错误是,控件只在viewstate中保存其html表示,而不在datasource中保存,所以我应该手动执行(例如在会话中)