将数据表从一个数据集克隆到另一个数据集的数据表

Clone DataTable from One Dataset to DataTable of Other DataSet

我正在尝试将数据表从一个数据集克隆到另一个数据集的数据表,但它不起作用。

Dataset ds = new Dataset();

 ds.Tables.Add("key");
 ds.Table["key"] = cust.Tables[0].Clone(); // This line is not working

以上代码给出以下错误

Property or indexer 'System.Data.DataTableCollection.this[int]' cannot be assigned to — it's read only

cust 也是一个数据集。谁能帮我解决这个问题

您遇到的错误与此类似:

Property or indexer 'System.Data.DataTableCollection.this[int]' cannot be assigned to -- it is read only

你做对了一次,然后你在下一行做错了。 该错误告诉您 cust.Tables[0] 是只读的。您不能为其分配任何值,因此您必须使用 Add() 方法:

DataSet cust = new DataSet(); // create source DataSet
cust.Tables.Add("sourceTable"); //add table to source

DataSet ds = new DataSet(); // create target DataSet
ds.Tables.Add((cust.Tables[0]).Clone()); //clone source table
(ds.Tables[0]).TableName = "keys"; // assign name

您需要将 ds.Tables[indexer] 包裹在括号 () 中,以便编译器将其视为数据表。

您应该分配一个 DataTable 变量以保持可读性:

var sourceTable = cust.Tables[0];
/* ... */
ds.Tables.Add(sourceTable.Clone());