将行从一个DataGridView复制到另一个DataGridView

Max*_*r88 1 c# winforms

我编写了一个在C#中连接到SQL数据库的应用程序.有两种形式.

我有第一种形式的DataGrid.Datagridview中有ID,AD,SOYAD等列.

我有第二种形式的DataGrid(frm4),Datagridview中有ID,AD,SOYAD等列.

我将ContextMenuStrip放在第一个DataGridView中.

我的问题是:我想在第二个DataGridView中添加在第一个DataGridView中选择的那些行.

  frm4.dataGridView1.Rows[0].Cells[0].Value = dataGridView1.CurrentRow.Cells[0].Value.ToString();
  frm4.dataGridView1.Rows[0].Cells[1].Value = dataGridView1.CurrentRow.Cells[1].Value.ToString();
  frm4.dataGridView1.Rows[0].Cells[2].Value = dataGridView1.CurrentRow.Cells[2].Value.ToString();
Run Code Online (Sandbox Code Playgroud)

我只能用上面的代码添加一行.但是,我想添加多行.我正在使用下面的代码.但是,它不起作用.

  for (int i = 0; i < length; i++)
  {
      frm4.dataGridView1.Rows[0].Cells[0].Value = dataGridView1.CurrentRow.Cells[0].Value.ToString();
      frm4.dataGridView1.Rows[0].Cells[1].Value = dataGridView1.CurrentRow.Cells[1].Value.ToString();
      frm4.dataGridView1.Rows[0].Cells[2].Value = dataGridView1.CurrentRow.Cells[2].Value.ToString();
  }
Run Code Online (Sandbox Code Playgroud)

Dav*_*all 11

以下代码有效,但可以改进.此外,您可能需要退一步,而是查看网格的数据源.例如,如果您使用绑定源,则应该能够复制该源并从那里创建第二个网格的源.

//to copy the rows you need to have created the columns:
foreach (DataGridViewColumn c in dataGridView1.Columns)
{                
    dataGridView2.Columns.Add(c.Clone() as DataGridViewColumn);
}

//then you can copy the rows values one by one (working on the selectedrows collection)
foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
    int index = dataGridView2.Rows.Add(r.Clone() as DataGridViewRow);
    foreach (DataGridViewCell o in r.Cells)
    {
        dataGridView2.Rows[index].Cells[o.ColumnIndex].Value = o.Value;
    }            
}
Run Code Online (Sandbox Code Playgroud)

  • 我试图通过foreach从选定的行中获取内容,然后执行var而不是DataGridViewRow,这让我很生气,因为那里没有方法,所有的东西都被当作对象。因此,这段代码对我有所帮助。VoteUp;)**孩子们不会不加思索地做`var`!** (2认同)