复制DataTable的一种方法
如果将程序返回的DataTable加入到自己定义的一个DataSet中,直接用ds.Tables.Add(dt)的方法,就会出现“该DataTable已属于另外一个DataSet”的错误。这时候我们需要建一个新的DataTable,并将原来的DataTable的结构及数据导入到新的DataTable中,这时候就可以使用下面的方法(当然方法并不是唯一的):
/// <summary>
/// 复制DataTable
/// </summary>
/// <param name="copyDt">数据源</param>
/// <param name="tableName">新DataTable名称</param>
/// <returns>复制后的DataTable</returns>
private DataTable CopyDataTable(DataTable copyDt, string tableName)
{
DataTable dt = new DataTable(tableName);
foreach (DataColumn columm in copyDt.Columns)
{
dt.Columns.Add(columm.ColumnName,columm.DataType);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
foreach (DataRow row in copyDt.Rows)
{
dt.BeginInit();
dt.ImportRow(row);
dt.EndInit();
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
return dt;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
posted on 2007-03-07 18:49 Daniel Pang 阅读(4802) 评论(7) 编辑 收藏 举报