Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将UserControl的数据保存到ViewState_C#_Asp.net_User Controls_Viewstate - Fatal编程技术网

C# 将UserControl的数据保存到ViewState

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

在我的用户控件中,我用集合填充列表框,并希望将数据保存在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;
} 

单击按钮时填充列表框。当我将帐户保存到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中保存,所以我应该手动执行(例如在会话中)