DataSet and DataGridView Datasource binding

2019-06-08 13:02发布

问题:

I have linked my DataGridView with a DataSet with all the values from one of my database tables. But what i want to do is filter my DataGridView to display certain values from my DataSet:

For example: (Where EmployeeID = 4),

is there any way of doing this without changing my initial binding object?

//Initial datasource
dgv.DataSource = DataSet1.Table[0];

//Some filter code here to display DataSet1 where employeeID = 1

//Show these results in the dgv without changing the initial binding.

回答1:

You can filter and sort using the DataTable.DefaultView.

DataTable dt = GetProductTable( );
dt.DefaultView.Sort = "ProductName";
dt.DefaultView.RowFilter = "CategoryID=1";
dataGridView1.DataSource = dt.DefaultView;

Example using the Northwind database:

select ProductID, ProductName, SupplierID, CategoryID, UnitPrice from Products;