How to serialize/de-serialize a custom DataSet

旧城冷巷雨未停 提交于 2019-12-14 01:20:32

问题


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.


回答1:


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.




回答2:


How about using Streams (sorry following code is not tested) but you get the idea

 DataSet selected = debugDisplay.SelectedDataSet;

  string ds1 = selected.GetXml();
  CostingDataSet tempDS = new CostingDataSet();
  System.IO.MemoryStream ms = new System.IO.MemoryStream(ds1.Length);
  selected.WriteXml(ms);
  ms.Position = 0;

  tempDS.ReadXml(ms);


来源:https://stackoverflow.com/questions/7891447/how-to-serialize-de-serialize-a-custom-dataset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!