将 DataGridView 的行复制到另一个 DataGridView [英] Copy DataGridView's rows into another DataGridView

查看:110
本文介绍了将 DataGridView 的行复制到另一个 DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有 2 个 DataGridView,我需要将行从一个复制到另一个.

So basically I've got 2 DataGridView and I need to copy the rows from one to the other.

到目前为止我已经尝试过:

So far I've tried:

DataGridViewRowCollection tmpRowCollection = DataGridView1.Rows;

DataGridViewRow[] tmpRowArray = new DataGridViewRow[tmpRowCollection.Count];
tmpRowCollection.CopyTo(tmpRowArray, 0);            

DataGridView2.Rows.AddRange((DataGridViewRow[]) tmpRowArray));

但它一直在说

"Row provided already belongs to a DataGridView control."

那么复制行内容的最佳方法是什么(两个 DataGridView 具有相同的列)?

So what's the best way to copy the content of the rows (both DataGridView have the same columns) ?

推荐答案

您使用以下链接中的功能

You use the function at the following link

private DataGridView CopyDataGridView(DataGridView dgv_org)
{
    DataGridView dgv_copy = new DataGridView();
    try
    {
        if (dgv_copy.Columns.Count == 0)
        {
            foreach (DataGridViewColumn dgvc in dgv_org.Columns)
            {
                dgv_copy.Columns.Add(dgvc.Clone() as DataGridViewColumn);
            }
        }

        DataGridViewRow row = new DataGridViewRow();

        for (int i = 0; i < dgv_org.Rows.Count; i++)
        {
            row = (DataGridViewRow)dgv_org.Rows[i].Clone();
            int intColIndex = 0;
            foreach (DataGridViewCell cell in dgv_org.Rows[i].Cells)
            {
                row.Cells[intColIndex].Value = cell.Value;
                intColIndex++;
            }
            dgv_copy.Rows.Add(row);
        }
        dgv_copy.AllowUserToAddRows = false;
        dgv_copy.Refresh();

    }
    catch (Exception ex)
    {
        cf.ShowExceptionErrorMsg("Copy DataGridViw", ex);
    }
    return dgv_copy;
}

http://canlu.blogspot.com/2009/06/copying-datagridviewrow-to-another.html

这篇关于将 DataGridView 的行复制到另一个 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆