C# 将 DataRow[] 转换为 DataTable 而不会丢失其 DataSet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11267653/
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
Convert a DataRow[] to DataTable without losing its DataSet
提问by Dante
I am working with DataSets and DataTables in C#.
我正在使用 C# 中的数据集和数据表。
My first problem was how to convert a DataRow[] object to DataTable, which I solved with this link:
我的第一个问题是如何将 DataRow[] 对象转换为 DataTable,我用这个链接解决了这个问题:
simple-way-to-convert-datarow-array-to-datatable
So, What I did was the following:
所以,我所做的是以下内容:
// Gets the rows according to the relation
DataRow[] rows = someDataRow.GetChildRows("the_table_relation");
DataTable newDataTable = rows.CopyToDataTable<DataRow>();
All the data that I am work with is in a single DataSet, so, my problem is that my object newDataTabledoes not contain the reference to my DataSet anymore (ie newDataTable.DataSetis equal to null).
我使用的所有数据都在单个 DataSet 中,因此,我的问题是我的对象newDataTable不再包含对我的 DataSet 的引用(即newDataTable.DataSet等于null)。
Is there a way to make the conversion without losing the reference to my DataSet??
有没有办法在不丢失对我的 DataSet 的引用的情况下进行转换?
Hope someone can help me.
希望可以有人帮帮我。
Thanks in advance
提前致谢
采纳答案by Jon Skeet
Presumably you already havea DataTable? If so, use an overload of CopyToDataTablewhich takes the existingtable as an argument:
想必你已经有一个DataTable?如果是这样,请使用将现有表作为参数的重载CopyToDataTable:
rows.CopyToDataTable<DataRow>(existingTable, LoadOption.Upsert);
Alternatively, could you just use DataTableCollection.Add(DataTable)?
或者,您可以使用DataTableCollection.Add(DataTable)?
dataSet.Tables.Add(table);
回答by Dan Norton
I believe the solution may be contained in Jon Skeet's answer
dataSet.Tables.Add(newDataTable)
我相信解决方案可能包含在 Jon Skeet 的回答中
dataSet.Tables.Add(newDataTable)
The thing is that the newDataTable doesn't have a DataSet child control but rather a DataSet parent control. That is, a DataSet can contain Tables while the newDataTable's DataSet is the "DataSet that owns newDataTable" which in the case of the table you're creating above is null until added to a DataSet.
问题是 newDataTable 没有 DataSet 子控件,而是一个 DataSet 父控件。也就是说,DataSet 可以包含表,而 newDataTable 的 DataSet 是“拥有 newDataTable 的 DataSet”,在您上面创建的表的情况下,它在添加到 DataSet 之前为空。
回答by lady
DataView DV = MyDataTable.AsDataView();
DV.RowFilter = "Id = '" + RecordId + "'";
DataTable newDataTable = DV.ToTable();

