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



我写了一个应用程序,连接到SQL数据库在c#。有两种形式

我有一个数据网格在第一种形式。Datagridview中有ID、AD、SOYAD等列。

我有一个数据网格在第二种形式(frm4),有那些列,如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();

我只能添加一行上代码。但是,我想添加多行。我用下面的代码。但是,它不工作。

  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();
  }

下面的代码可以工作,但是可能还需要改进。此外,您可能希望后退一步,转而查看网格的数据源。如果你正在使用绑定源,例如,你应该能够复制它,并从那里创建第二个网格的源。

//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;
    }            
}

假设这是Windows窗体应用程序

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (this.dataGridView2.DataSource != null)
    {
        this.dataGridView2.DataSource = null;
    }
    else
    {
        this.dataGridView2.Rows.Clear();
    }
    for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
    {
        int index = dataGridView2.Rows.Add();
        dataGridView2.Rows[index].Cells[0].Value = dataGridView1.SelectedRows[i].Cells[0].Value.ToString();
        dataGridView2.Rows[index].Cells[1].Value = dataGridView1.SelectedRows[i].Cells[1].Value.ToString();
        .....
    }
}

尝试使用DataGridView的Add方法。此时,您将覆盖第一行上的任何值。通过使用Add方法,您可以向DataGridView添加额外的行。

相关内容

最新更新