I have a winforms app that uses a strongly typed custom DataSet for holding data for processing. It gets populated with data from a database.
I have a user control that takes any custom dataset and displays the contents in a data grid. This is used for testing and debugging. To make the control reusable, I treat the custom dataset as a normal System.Data.DataSet.
I have extended the control to allow the dataset to be saved to an XML file and also load previously saved XML files.
What I'm now trying to do is take the loaded data file, which is treated as a standard DataSet, and cast it back to the Custom Dataset. This shouldn't be difficult but I am getting the following System.InvalidCastException message:
Unable to cast object of type 'System.Data.DataSet' to type 'CostingDataSet'.
Here is an example of the problem code (It's the last line of the 3 that generates the exception):
DataSet selected = debugDisplay.SelectedDataSet;
CostingDataSet tempDS = new CostingDataSet();
tempDS = (CostingDataSet)selected.Copy();
Can anyone give me a steer on how to fix this?
Edit: Following the comments from nEM I implemented this and all was good.
foreach (System.Data.DataTable basicDT in selected.Tables)
{
DataTable dt = tempDS.Tables[basicDT.TableName];
dt = basicDT.Copy();
}
In addition, the code suggested by SSarma also works.
From what I have gathered from this website, you can't cast a regular dataset into a typed one which makes sense as its strongly typed and has certain specifications. If you have saved it as a regular dataset, when you deserialise it, the XML has no recollection of it ever being created as a typed dataset. For the xml file, you only ever saved a regular dataset so it is equivalent to trying to convert a standard dataset into a typed one by explicit casting which isn't allowed.
You could create a populate method that takes in a regular dataset as an argument which copies all the data into your typed dataset.
This is assuming that you are serialising it as a standard dataset.