博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

#将datagridview转datatable

Posted on 2011-04-12 21:46  moss_tan_jun  阅读(1483)  评论(0编辑  收藏  举报

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Linq;
using System.Text;

namespace Test

{
    public class DataTransition
    {
        /// <summary>
        /// datagridview转datatable
        /// </summary>
        /// <param name="dv"></param>
        /// <returns></returns>
        public static DataTable dvtodt(DataGridView dv)
        {
            DataTable dt = new DataTable();
            DataColumn dc;
            for (int i = 0; i < dv.Columns.Count; i++)
            {
                dc = new DataColumn();
                dc.ColumnName = dv.Columns[i].HeaderText.ToString();
                dt.Columns.Add(dc);
            }
            for (int j = 0; j < dv.Rows.Count; j++)
            {
                DataRow dr = dt.NewRow();
                for (int x = 0; x < dv.Columns.Count; x++)
                {
                    dr[x] = dv.Rows[j].Cells[x].Value;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}