日期:2014-05-17  浏览次数:20837 次

dataGridView控件内容的复制。
在不绑定数据,动态添加列和行的情况下。
这是我能想到的办法…

dataGridView2.Columns.Clear(); //复制前先清空
            for (int i = 0; i < dataGridView1.Columns.Count; i++) //添加列 奇怪,明明添加的是dgv1列的Clone,却还要用as转换?
                dataGridView2.Columns.Add(dataGridView1.Columns[i].Clone() as DataGridViewColumn);
            for (int i = 0; i < dataGridView1.Rows.Count; i++) //添加行
                dataGridView2.Rows.Add(dataGridView2.Rows[i].Clone());
            //获取单元格的值
            for (int rowscount = 0; rowscount < dataGridView1.Rows.Count; rowscount++)
            {
                for (int cellscount = 0; cellscount < dataGridView1.Rows[rowscount].Cells.Count; cellscount++)
                    dataGridView2.Rows[rowscount].Cells[cellscount].Value = dataGridView1.Rows[rowscount].Cells[cellscount].Value;
            }


为什么要用Clone?因为转换成DataTable也好,直接添加也好,都会提示“添加的列已在dataGridView”空间中。
想要用=直接复制,结果只得到一个引用指向…
奇怪,为什么列和行能给Clone,整个Table就不能呢?
总感觉这方法不够优雅,不知道各位前辈们有没有更好的办法……

------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/system.data.datatable.copy.aspx
DataTable.Copy
------解决方案--------------------
按照3楼我给出的写法似乎还是比较复杂,带循环的,已经实现,我就不上代码了。
你可以考虑用2楼说的DataTable,DataTable操作很方便,处理完毕后直接给datagridview绑定即可。