Reputation: 129
what i am trying to do is write a sepprate function that is in the business logic of my Windows form application. this function recieves the xml file path and the datagridview object as arguments.
This is supposed to work:
DataTable dt = new DataTable();
dt = (DataTable)datagridview.DataSource;
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(xml_file, System.Data.XmlWriteMode.IgnoreSchema);
But i have a error everytime with the line:
dt = (DataTable)datagridview.DataSource;
[System.InvalidCastException] = {"Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'."}
so i was advised in another blog to try this:
BindingSource bs = (BindingSource)dgv.DataSource;
dt = (DataTable)bs.DataSource;
but i get
[System.InvalidCastException] = {"Unable to cast object of type 'ExportDataTestApp.NorthwindDataSet' to type 'System.Data.DataTable'."}
i have searched and tryed everything i would not be supprised if it is something simple as i am new to c# but i need help please
Upvotes: 1
Views: 1804
Reputation: 273274
You're almost there.
BindingSource bs = (BindingSource)dgv.DataSource;
DataSet ds = (DataSet)bs.DataSource;
DataTable dt = ds.Tables["Customers"]; // or Tables[0]
Apparently you are binding with DataSourse=myDataSet, DataMember="Tablename"
Upvotes: 2