2011-10-02 69 views
2

我有一個用戶控件AutomatedFeedGridView.ascx這實質上是一個GridView。它有一個公共財產Category,它使用控件在頁面上傳入。GridView綁定後獲取項目

我遇到的問題是我想根據調用頁面上的下拉列表進行過濾。

下面是對AutomatedFeedGridView控制代碼隱藏:

// The feed category 
public Feeds.FeedCategory Category { get; set; } 


protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     List<AutomatedFeed> x = Feeds.GetAutomatedFeed(Category); 
     gvAutomatedFeed.DataSource = x; 
     gvAutomatedFeed.DataBind(); 
    } 

    else 
    { 
     List<AutomatedFeed> x = (List<AutomatedFeed>)gvAutomatedFeedCategory.DataSource; 

     foreach (AutomatedFeed y in x) 
     { 
      // if condition is not met, hide y 
     } 
    } 

所以在第一次加載時,GridView勢必AutomatedFeed對象的名單。在任何後續調用(由包含控件的頁面上的回發引起)我想運行一些代碼來過濾出GridView中的一些項目。問題是這樣的一行:

List<AutomatedFeed> x = (List<AutomatedFeed>)gvAutomatedFeedCategory.DataSource; 

我已經嘗試了所有的解決方案here,但他們都不上班,我總是不設置到實例錯誤的對象引用。我錯過了什麼,或者我是以完全錯誤的方式做這件事?

我知道我可以很容易地再打一個電話給Feeds.GetAutomatedFeed(Category),但是做一個更好的方法來做另一個存儲過程調用?

回答

1

您可以在會話數據源存儲爲Session["x"] = x ;

當頁面後回檢索它早在List<AutomatedFeed> x = List<AutomatedFeed>)Session["x"];

UPDATE:

DataSource屬性將是無效的,除非你明確地重新分配和在每次回傳時重新綁定它。

您可以使用Session,Cache或ViewState來保存數據源。但它會佔用更多的內存。

+1

可能更好的將它保存在'ViewState'中 – Magnus

+0

是的,更新我的回答 – Damith

+0

謝謝,這足以解決我的問題,而不必重新執行存儲過程。我之前沒有以編程方式使用過'ViewState'。 [此視頻](http://www.asp.net/general/videos/how-do-i-save-and-load-view-state-information-for-a-custom-web-server-control)是簡單但解釋了其他人感興趣的基礎知識。 – Arj

0

該控件僅在page.load後生成並填充,因此它不包含任何數據。