共用方式為


如何:使用 Windows Forms BindingSource 元件排序和篩選 ADO.NET 資料

您可以透過 SortFilter 屬性公開 BindingSource 控制項的排序和篩選功能。 當基礎資料來源是 IBindingList 時,您可以套用簡單的排序,當資料來源是 IBindingListView 時,您可以套用篩選和進階排序。 Sort 屬性需要標準 ADO.NET 語法:字串代表資料來源中資料行的名稱,後面接著 ASCDESC,表示清單應該以遞增或遞減順序排序。 您可以藉由以逗號分隔符分隔每個資料行,來設定進階排序或多資料行排序。 Filter 屬性採用字串運算式。

注意

在連接字串內儲存機密資訊 (例如密碼) 會影響應用程式的安全性。 使用 Windows 驗證 (也稱為整合式安全性) 是控制資料庫存取的更安全方式。 如需詳細資訊,請參閱保護連線資訊

使用 BindingSource 篩選資料

  • Filter 屬性設定為所要的運算式。

    在下列程式碼範例中,運算式為資料行名稱,後面接著您要用於資料行的值。

BindingSource1.Filter = "ContactTitle='Owner'";
BindingSource1.Filter = "ContactTitle='Owner'"

使用 BindingSource 排序資料

  1. Sort 屬性設定為您想要的資料行名稱,後面接著 ASCDESC,表示為遞增或遞減順序。

  2. 以逗號分隔多個資料行。

BindingSource1.Sort = "Country DESC, Address ASC";
BindingSource1.Sort = "Country DESC, Address ASC"

範例

下列程式碼範例會將 Northwind 範例資料庫的 Customers 資料表中的資料載入 DataGridView 控制項,然後篩選並排序顯示的資料。

private void InitializeSortedFilteredBindingSource()
{
    // Create the connection string, data adapter and data table.
    SqlConnection connectionString =
         new SqlConnection("Initial Catalog=Northwind;" +
         "Data Source=localhost;Integrated Security=SSPI;");
    SqlDataAdapter customersTableAdapter =
        new SqlDataAdapter("Select * from Customers", connectionString);
    DataTable customerTable = new DataTable();

    // Fill the adapter with the contents of the customer table.
    customersTableAdapter.Fill(customerTable);

    // Set data source for BindingSource1.
    BindingSource1.DataSource = customerTable;

    // Filter the items to show contacts who are owners.
    BindingSource1.Filter = "ContactTitle='Owner'";

    // Sort the items on the company name in descending order.
    BindingSource1.Sort = "Country DESC, Address ASC";

    // Set the data source for dataGridView1 to BindingSource1.
    dataGridView1.DataSource = BindingSource1;
}
Private Sub InitializeSortedFilteredBindingSource()

    ' Create the connection string, data adapter and data table.
    Dim connectionString As New SqlConnection("Initial Catalog=Northwind;" & _
        "Data Source=localhost;Integrated Security=SSPI;")
    Dim customersTableAdapter As New SqlDataAdapter("Select * from Customers", _
        connectionString)
    Dim customerTable As New DataTable()

    ' Fill the adapter with the contents of the customer table.
    customersTableAdapter.Fill(customerTable)

    ' Set data source for BindingSource1.
    BindingSource1.DataSource = customerTable

    ' Filter the items to show contacts who are owners.
    BindingSource1.Filter = "ContactTitle='Owner'"
    ' Sort the items on the company name in descending order.
    BindingSource1.Sort = "Country DESC, Address ASC"

    ' Set the data source for dataGridView1 to BindingSource1.
    dataGridView1.DataSource = BindingSource1

   
End Sub

編譯程式碼

若要執行此範例,請將程式碼貼入表單,其中包含名為 BindingSource1BindingSource,以及名為 dataGridView1DataGridView。 處理表單的 Load 事件,並在載入事件處理常式方法中呼叫 InitializeSortedFilteredBindingSource

另請參閱