C# 将 dataRow 传输到新数据集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1206160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
transfer dataRow to new dataset
提问by JL.
I have a dataset that I read in from a complex xml structure....
我有一个从复杂的 xml 结构中读入的数据集....
here is a basic version of it, for the sake of the question
为了这个问题,这是它的基本版本
<cars>
<car>
<carName>Golf</carName>
<engine>
<model></model>
</engine>
<//car>
<car>
<carName>Dodge</carName>
<engine>
<model></model>
</engine>
<//car>
</cars>
Firstly I create the dataset to get the whole document.... (and I read this from file)
首先,我创建数据集以获取整个文档......(我从文件中读取了这个)
DataSet dsCars = new DataSet();
dsConfiguration.ReadXml("allcars.xml"));
Next I want to loop through all car rows.. to do this I use the following code:
接下来我想遍历所有汽车行..为此我使用以下代码:
foreach(DataRow carDataRow in dsCars.Tables["Car"].Rows)
Now in this loop, I want to inject the car row (AND all its sub content) into a new dataset
现在在这个循环中,我想将汽车行(及其所有子内容)注入新数据集
So in the foreach loop I have code to
所以在 foreach 循环中我有代码
- Create the new dataset
- Create a new datatable = CarList2
- Import the row using : tempTaskTable2.ImportRow(carDataRow);
- 创建新数据集
- 创建一个新的数据表 = CarList2
- 使用以下方法导入行:tempTaskTable2.ImportRow(carDataRow);
But when I serialize to file using: tempTaskDS.WriteXml(@"c:\test.xml");
但是当我使用以下命令序列化到文件时: tempTaskDS.WriteXml(@"c:\test.xml");
The newly created datatable = Carlist2 is blank and contains no data at all...
新创建的数据表 = Carlist2 是空白的,根本不包含任何数据......
What am I doing wrong?
我究竟做错了什么?
采纳答案by Jonas Elfstr?m
I'm not sure what you are trying to do but you could try this in the loop:
我不确定您要做什么,但您可以在循环中尝试:
DataSet tempTaskDS = new DataSet("tempCars");
tempTaskDS.Tables.Add("Cars");
tempTaskDS.Tables[0].Rows.Add(carDataRow);
回答by Colin
First make sure your target DataSet / DataTable is the same as the source DataSet / DataTable with regards to column count, column typesetc. then use
首先确保您的目标 DataSet / DataTable 在列数、列类型等方面与源 DataSet / DataTable 相同,然后使用
targetDataSet.Tables["CarList2"].ImportRow(sourceRow)