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

C#如何从DataGridView控件数据,转成获取DataTable

Posted on 2011-04-07 22:47  moss_tan_jun  阅读(7970)  评论(1编辑  收藏  举报
 public DataTable GetDgvToTable(DataGridView dgv)
        {
            DataTable dt
= new DataTable();
           
for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc
= new DataColumn(dgv.Columns[count].Name.ToString());
                dt.Columns.Add(dc);
            }
           
for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr
= dt.NewRow();
               
for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub]
= Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
           
return dt;
        }