如何序列化/反序列化的自定义数据集 [英] How to serialize/de-serialize a custom DataSet

查看:215
本文介绍了如何序列化/反序列化的自定义数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用用于保存数据进行处理的强类型DataSet中定制一个WinForms应用程序。它被填充数据库中的数据。

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.

我有需要的任何自定义数据并显示内容数据网格的用户控件。这用于测试和调试。为了使控制可重复使用的,我把自定义的数据集作为一个正常的System.Data.DataSet中。

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.

我已经扩展了控制,使数据被保存到一个XML文件还加载以前保存的XML文件。

I have extended the control to allow the dataset to be saved to an XML file and also load previously saved XML files.

什么我现在要做的就是把加载的数据文件,它被视为一个标准的数据集,然后将其丢返回自定义数据集。这不应该是困难的,但我得到以下System.InvalidCastException消息:

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:

无法转换类型System.Data这的'对象。数据集键入
'CostingDataSet'。

Unable to cast object of type 'System.Data.DataSet' to type 'CostingDataSet'.

这是问题的代码示例(它的最后一行3产生除外):

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?

编辑:
继NEM我实现了这一点,一切都很好的意见

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();
}



此外,SSarma建议代码也可以。

In addition, the code suggested by SSarma also works.

推荐答案

这是我从的本网站,你可以不投一个普通数据集到一个类型化的其中一个有意义的,因为它的强类型,具有一定的规范。如果已将其作为常规的数据集,当你deserialise吧,XML具有以往任何时候都被创建为一个类型化的DataSet没有它的回味。为XML文件,你永远只能保存一个普通的数据集,因此相当于试图标准的数据转换成键入一个又明确铸造这是不允许的。

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.

这篇关于如何序列化/反序列化的自定义数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆