2010-06-04 33 views
0

我有一個從有序列表中接受值的gridview。我想在將這些值放入gridview之前過濾這些值,而不將值從列表中取出。在gridview上過濾數據,並將sortedlist作爲數據源

有沒有簡單的方法來做到這一點?或者我必須通過另一個列表重定向數據並將gridview指向它?

回答

1

可能有很多方法可以做到這一點,但沒有一種是魔法。都涉及一些工作。

如果列表在內存中,是的,您必須在綁定到網格之前通過篩選過程清洗列表。

如果列表來自數據庫,那麼您應該在數據庫級別進行過濾。我更喜歡這樣做的方式是將網格綁定到ObjectDataSource。您還可以將UI中的其他控件綁定爲ObjectDataSource中的選擇參數。 (你也可以做排序和分頁通過ObjectDataSource控件,讓一切都可以在你的數據庫查詢建立和網格只有結合你要顯示的數據。)

這裏有一個ObjectDataSource完全配置:

<asp:ObjectDataSource ID="CustomerObjectDataSource" runat="server" 
    EnablePaging="True" 
    MaximumRowsParameterName="totalRows" 
    StartRowIndexParameterName="firstRow" 
    TypeName="Northwind.Business.CustomerSource" 
    DataObjectTypeName="Northwind.Business.CustomerDTO" 
    SelectMethod="Load" 
    UpdateMethod="Save" 
    InsertMethod="Insert" 
    DeleteMethod="Delete" 
    SelectCountMethod="CustomerCount" 
    SortParameterName="sortExpression"> 
    <SelectParameters> 
     <asp:ControlParameter ControlID="ddlRegion" Name="region" 
      PropertyName="SelectedValue" /> 
    </SelectParameters> 
</asp:ObjectDataSource>  

請注意,它綁定到數據庫查詢中用於選擇的下拉列表。

這裏的網格,結合:

<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False" 
    DataSourceID="CustomerObjectDataSource" 
    DataKeyNames="CustomerID" 
    AllowPaging="True" 
    AllowSorting="True" AutoGenerateDeleteButton="True" 
    AutoGenerateEditButton="True" AutoGenerateSelectButton="True" 
    onrowdeleted="GridView1_RowDeleted" onrowupdated="GridView1_RowUpdated"> 
    <Columns> ..... 

這裏的ObjectDataSource控件綁定到要選擇的方法:

public static List<CustomerDTO> Load(
    int totalRows, 
    int firstRow, 
    string sortExpression, 
    string region) 
{ ... } 

Load方法構建查詢,並運行它,然後返回數據。它可以是IEnumerable或List,或者是DataSet或DataTable。這應該讓你開始。

一件好事是,代碼隱藏現在幾乎是空的。它只需要處理與綁定,排序或分頁無關的事件。

+0

哇,我沒想到會有這麼完整的解釋。非常感謝! – Moox 2010-06-04 13:11:36

+0

不客氣!當你有一個演示應用程序可以完全滿足某人的要求時,它會有所幫助。我在我們本地的.NET用戶組建立了這個討論會。 – 2010-06-04 13:51:06

相關問題