Reputation: 112
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];
Upvotes: 0
Views: 2532
Reputation: 3196
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.
Upvotes: 1
Reputation: 5251
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.
Upvotes: 0
Reputation: 2824
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?
Upvotes: 0