How to serialize/de-serialize a custom DataSet

10,916

Solution 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.

Solution 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);
Share:
10,916
TeamWild
Author by

TeamWild

A former software developer and team leader working with C#, I now work as a solution architect for a large health and beauty retailer based in Nottingham.

Updated on June 27, 2022

Comments

  • TeamWild
    TeamWild almost 2 years

    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.