2010-08-05 63 views
1

在我的用戶控件中,我使用集合填充列表框,並希望將數據保存在viewstate \ controlstate中以便進一步使用autopostback。將UserControl的數據保存到ViewState

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列表框爲空時,不顯示集合良好。這種行爲的推理是什麼?

+3

Андрей,этотыминусешьпосты ?) – abatishchev 2010-08-05 11:48:06

+0

沒有傢伙。非常感謝。我的錯誤,該控件只保存其在viewstate html表示,但數據源不是,所以我應該手動(例如會話) – 2010-08-05 15:41:41

回答

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

(不要忘記訂閱DataBinding事件標記你的ListBox)

此外,我建議您將訪問封裝到ViewState

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

爲什麼downvote ..? – abatishchev 2010-08-05 11:05:23

+0

我知道你的意思。我有兩個,沒有解釋! – 2010-08-05 11:32:47