0
dataGridView1.DataSource = myDataSet1;
dataGridView1.DataMember = "SomeTable";

And now I want to get the refference to DataTable back from my dataGridView1. Something like this:

DataTable dt = (DataTable)dataGridView1.DataSource... ;

I'm aware of BindingContext, but couldn't find the way to get DataTable refference back.


Got it.

DataSet dataSet = (DataSet)dataGridView1.DataSource;
string tableName = dataGridView1.DataMember;
DataTable dt =dataSet.Tables[tableName];
Excelan
  • 112
  • 3
  • 10

3 Answers3

1

you are assigning Dataset as datasource to your gridview. So, the line below would help u.

DataTable dt = ((DataSet)dataGridView1.DataSource).Tables[index];

Assuming that you have only one datatable in your dataset. you can also use your table name instead of index.

AnarchistGeek
  • 3,049
  • 6
  • 32
  • 47
0

You can convert it in this way

BindingSource bs = (BindingSource )dgrid.DataSource;
DataTable tCxC = (DataTable ) bs.DataSource

Look at this question How can I export a GridView.DataSource to a datatable or dataset?

Community
  • 1
  • 1
Mulesoft Developer
  • 2,664
  • 5
  • 28
  • 41
0

You can either be resilient (to avoid null error) or take a chance.

The short version is:

DataTable dt = ((DataSet) dataGridView1.DataSource).Tables[0];

A more resilient approach (not assuming the view is bound to a DataSet):

DataSet ds = dataGridView1 as DataSet;  
if (ds != null)  DataTable dt = ds.Tables[0];  

Obviously you can inspect/check the number of tables in the DataSet.

kaj
  • 5,133
  • 2
  • 21
  • 18