当我们使用DataTable的时候,取到其中的一行dataRow,然后将其Add()到另外的一个表。如果直接进行Add()的话,就会出现一个异常 "此行已经属于另一个表"。
简单例子:
1 private void OperateDataTable() 2 { 3 DataTable dataTableA = new DataTable("Table A"); 4 DataColumn dataColumn; 5 DataRow dataRow; 6 7 dataColumn = new DataColumn(); 8 dataColumn.ColumnName = "ID"; 9 dataColumn.DataType = typeof(int); //Type.GetType("System.Int32"); 10 dataTableA.Columns.Add(dataColumn); 11 12 dataColumn = new DataColumn(); 13 dataColumn.ColumnName = "Name"; 14 dataColumn.DataType = typeof(string); 15 dataTableA.Columns.Add(dataColumn); 16 17 for (int i = 0; i < 10; i++) 18 { 19 dataRow = dataTableA.NewRow(); 20 21 dataRow["ID"] = i; 22 dataRow["Name"] = $"{i}_Name"; 23 24 dataTableA.Rows.Add(dataRow); 25 } 26 27 DataTable dataTableB = new DataTable("Table B"); 28 29 dataColumn = new DataColumn(); 30 dataColumn.ColumnName = "ID"; 31 dataColumn.DataType = typeof(int); //Type.GetType("System.Int32"); 32 dataTableB.Columns.Add(dataColumn); 33 34 dataColumn = new DataColumn(); 35 dataColumn.ColumnName = "Name"; 36 dataColumn.DataType = typeof(string); 37 dataTableB.Columns.Add(dataColumn); 38 39 for (int i = 10; i < 20; i++) 40 { 41 dataRow = dataTableB.NewRow(); 42 43 dataRow["ID"] = i; 44 dataRow["Name"] = $"{i}_Name"; 45 46 dataTableB.Rows.Add(dataRow); 47 } 48 49 if (dataTableB.Rows.Count > 0 && dataTableB.Rows[0] != null) 50 { 51 DataRow row = dataTableB.Rows[0]; 52 53 dataTableA.Rows.Add(row); // 这里会出异常 54 } 55 }
解决方案:
if (dataTableB.Rows.Count > 0 && dataTableB.Rows[0] != null) { DataRow row = dataTableB.Rows[0]; dataTableA.Rows.Add(row.ItemArray); }
这样就可以顺利运行,并解决啦!