如何:使用 Windows 窗体 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

编译代码

若要运行此示例,请将代码粘贴到包含 BindingSource(名为 BindingSource1)和 DataGridView(名为 dataGridView1)的窗体中。 处理窗体的 Load 事件,并在加载事件处理程序方法中调用 InitializeSortedFilteredBindingSource

另请参阅