2013-03-04 71 views
0

我有興趣在應用某些過濾器後獲取用戶在網格視圖中看到的所有數據。例如,原始網格的數據源包含10條記錄,但用戶應用一個過濾器後,只剩下5個過濾器,我想將這5個記錄放入一個列表中。這如何實現?網格視圖過濾的數據

+0

我編輯了自己的冠軍。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2013-03-04 14:40:04

+0

這取決於你如何過濾GridView。你寫過那些例程嗎? – 2013-03-04 14:44:11

+0

如果您提供了一些示例代碼,您將得到更好的答案。什麼樣的過濾器?他們如何被應用?等。 – 2013-03-04 14:45:36

回答

0

假設您的網格綁定了一些集合,然後在回發中,您可以獲取gridview的數據源,應用您的過濾器並將其保存到新的集合中。

喜歡的東西:

var datasource = yourGridView.DataSource as List<someType>; 
var filteredResults = datasource.Where(...); // apply your filters inside the Where 

顯然,你使用你的代碼是什麼代替例如變量名/類型。

+0

我應該指出,我將你的問題解釋爲更多的「我該如何處理gridview綁定的集合」,而不是「如何將過濾器應用於集合」。如果你問後者,請儘可能提供更多的見解和一些代碼。 – 2013-03-04 14:47:28

0

下面有一種內置的方式來篩選網格視圖的一個可愛的小例子:

protected void btnSearch(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection("MyConn"); 
    SqlCommand cmd = new SqlCommand(); 
    SqlDataAdapter sda = new SqlDataAdapter(cmd); 
    DataTable dt = new DataTable(); 

    cmd.Connection = con; 
    cmd.CommandText = "SELECT * FROM CustomerTable WHERE NumberOfCustomer = @NumberOfCustomer"; 
    cmd.Parameters.AddWithValue("NumberOfCustomer", TextBox1.Text); 

    try 
    { 
     con.Open(); 
     sda.Fill(dt); 
    } 
    catch (Exception ex) 
    { 
     Response.Write(ex.Message); 
    } 
    finally 
    { 
     con.Close(); 
    } 

    GridView1.DataSource = dt; 
    GridView1.DataBind(); 
} 

然後到數據源綁定到一個列表:

protected void bindToList(object sender, EventArgs e) 
{ 
    var datasource = GridView1.DataSource as List<Customers>; 

    if (!IsPostBack) 
    { 
     DropDownList ddl = new DropDownList(); 
     ddl.DataTextField = "Name"; 
     ddl.DataValueField = "Id"; 
     ddl.DataSource = datasource; 
     ddl.DataBind(); 

     ddl.SelectedValue = list.Find(o => o.Selected == true).Id.ToString(); 
    } 
}