Jonny Piazzi
Jonny Piazzi

Reputation: 3794

Get DataTable from DataGridView respecting filters and sorting

I have a System.Windows.Forms.DataGridView filled with data. I'm using some code like this:

System.Data.DataTable dataTable1;
System.Windows.Forms.BindingSource bindingSource1;
System.Windows.Forms.DataGridView dataGridView1;

// (...)

bindingSource1.DataSource = dataTable1;

dataGridView1.DataSource = bindingSource1;

bindingSource1.Filter = "Some Filter Here";

What I need now is to recover the data that are in dataGridView1. But it don't need to be complicated. my dataGridView1 is readonly so the only thing I need is respect the order and the filter used, and export the data to a DataTable.

Anyone can help me?

Upvotes: 2

Views: 4901

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73492

If I understand you correctly, you need the filtered rows displaying in DataGridView as DataTable. You can make use of DataTable.DefaultView property for this purpose which includes all the filters.

Try this

BindingSource bs = (BindingSource)dataGridView1.DataSource;
DataTable table = (DataTable)bs.DataSource;
DataTable filtered = table.DefaultView.ToTable();// here we get filtered datatable

Upvotes: 9

Related Questions