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

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

注意

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

使用 BindingSource 篩選資料

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

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

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

使用 BindingSource 排序資料

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

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

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

範例

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

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

編譯程式碼

若要執行此範例,請將程式碼貼到包含 BindingSource 具名和 DataGridView 具名 BindingSource1dataGridView1 的表單中。 處理表單的事件, Load 並在 load 事件處理常式方法中呼叫 InitializeSortedFilteredBindingSource

另請參閱