分享

c# 将DataGridViewRows转换为DataTable数据

 羊玉wngbx 2019-02-16
/// <summary>
  1.         /// 将DataGridViewRows转换为DataTable数据  
  2.         /// </summary>  
  3.         /// <param name="Listrows">DataGridView的行集合</param>  
  4.         /// <param name="dtSource">源数据表</param>  
  5.         /// <param name="colum">映射关系</param>  
  6.         /// <param name="dtDestination">目的数据表</param>  
  7.         /// <returns>返回新的DataTable</returns>  
  8.         public static DataTable Getdatatable(DataGridViewRowCollection Listrows, DataTable dtSource, 
  9.                      string[,] colum, DataTable dtDestination)  
  10.         {  
  11.             //  string[,] colum = { { "id1", "id2" }, { "name1", "name2" } };  
  12.             //  colum是源DataGridViewRow到目标DataRow的映射关系  
  13.             DataTable dtNew = dtSource.Clone();//复制表结构  
  14.             foreach (DataGridViewRow dgvr in Listrows)  
  15.             {  
  16.                //转换成数据行DataRow  
  17.                 DataRow dataRow = (dgvr.DataBoundItem as DataRowView).Row;  
  18.                 dtNew.ImportRow(dataRow);  //添加DataRow到DataTable  
  19.             }  
  20.             string[] copy = new string[colum.Length / 2];  
  21.             for (int i = 0; i < colum.Length / 2; i++)  
  22.             {  
  23.                 copy[i] = colum[i, 0];  //获取源数据要的列  
  24.             }  
  25.             //复制源表结构和数据,并只保留copy数据中的列  
  26.             DataTable dtNew2 = dtNew.DefaultView.ToTable(false, copy);
  27.             if (dtDestination != null)  
  28.             {  
  29.                 for (int j = 0; j < dtNew2.Rows.Count; j++)  
  30.                 {  
  31.                     DataRow row = dtDestination.NewRow();  
  32.                     for (int f = 0; f < colum.Length / 2; f++)  
  33.                     {  
  34.                         //将源表中每行的各列数据复制到对应的目的表的行中
  35.                         row[colum[f, 1]] = dtNew2.Rows[j][colum[f, 0]]; 
  36.                     }  
  37.                     dtDestination.Rows.Add(row); //添加到目的表  
  38.                 }  
  39.             }  
  40.             return dtDestination;  
  41.         }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多