Copy DataGridView's rows into another DataGridView

前端 未结 4 1236
[愿得一人]
[愿得一人] 2020-12-19 06:20

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 t         


        
相关标签:
4条回答
  • 2020-12-19 06:57

    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

    0 讨论(0)
  • 2020-12-19 07:01

    I would recommend using a backing DTO for this. Instead of dealing with the rows directly, create a DTO that contains all the columns of your GridViews, then use a List of them as your DataSource. Then, all you have to do to add/remove rows is to add/remove DTOs in the list.

    0 讨论(0)
  • 2020-12-19 07:05

    you need to first clone the row from the original then add to new view. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone.aspx

    0 讨论(0)
  • 2020-12-19 07:11

    just write this:

    copyDGV.DataSource = mainDGV.DataSource;        
    
    0 讨论(0)
提交回复
热议问题