码迷,mamicode.com
首页 > 其他好文 > 详细

DataRow[]转DataTable

时间:2015-05-21 12:52:23      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:

   DataRow[]转DataTable 经常忘记了会直接Add(DataRow),这样会报以下错误”此行已属于另一个表“,要用DataRow.ItemArray

  错误写法:

  

        public DataTable ToDataTable(DataRow[] rows)
        {
            if (rows == null || rows.Length == 0) return null;
            DataTable tmp = rows[0].Table.Clone();  // 复制DataRow的表结构
            foreach (DataRow row in rows)
                tmp.Rows.Add(row);  // 将DataRow添加到DataTable中
            return tmp;
        }

正确写法:


        public DataTable ToDataTable(DataRow[] rows)
        {
            if (rows == null || rows.Length == 0) return null;
            DataTable tmp = rows[0].Table.Clone();  // 复制DataRow的表结构
            foreach (DataRow row in rows)
                tmp.Rows.Add(row.ItemArray);  // 将DataRow添加到DataTable中
            return tmp;
        }


DataRow[]转DataTable

标签:

原文地址:http://blog.csdn.net/wrfccl/article/details/45888877

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!