19
2012
07

将DataGridViewRows转换为DataTable数据


.Net WinForm代码:

        /// <summary>
        /// 将DataGridViewRows转换为DataTable数据
        /// </summary>
        /// <param name="Listrows">DataGridView的行集合</param>
        /// <param name="dtSource">源数据表</param>
        /// <param name="colum">映射关系</param>
        /// <param name="dtDestination">目的数据表</param>
        /// <returns>返回新的DataTable</returns>
        public static DataTable Getdatatable(DataGridViewRowCollection Listrows, DataTable dtSource, string[,] colum, DataTable dtDestination)
        {
            //  string[,] colum = { { "id1", "id2" }, { "name1", "name2" } };  //colum是源DataGridViewRow到目标DataRow的映射关系
            DataTable dtNew = dtSource.Clone();//复制表结构
            foreach (DataGridViewRow dgvr in Listrows)
            {
                DataRow dataRow = (dgvr.DataBoundItem as DataRowView).Row;  //转换成数据行DataRow
                dtNew.ImportRow(dataRow);  //添加DataRow到DataTable
            }
            string[] copy = new string[colum.Length / 2];
            for (int i = 0; i < colum.Length / 2; i++)
            {
                copy[i] = colum[i, 0];  //获取源数据要的列
            }
            DataTable dtNew2 = dtNew.DefaultView.ToTable(false, copy);//复制源表结构和数据,并只保留copy数据中的列
            if (dtDestination != null)
            {
                for (int j = 0; j < dtNew2.Rows.Count; j++)
                {
                    DataRow row = dtDestination.NewRow();
                    for (int f = 0; f < colum.Length / 2; f++)
                    {
                        row[colum[f, 1]] = dtNew2.Rows[j][colum[f, 0]]; //将源表中每行的各列数据复制到对应的目的表的行中
                    }
                    dtDestination.Rows.Add(row); //添加到目的表
                }
            }
            return dtDestination;
        }




版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。