【问题标题】:Copying rows from one DataGridView to another将行从一个 DataGridView 复制到另一个
【发布时间】:2011-07-31 18:01:13
【问题描述】:

我用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();

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

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

【问题讨论】:

  • 我刚刚注意到它被标记为 asp.net - 这是正确的吗?因为,DataGridView 是 Winform 而不是 Webforms 控件。

标签: c# winforms


【解决方案1】:

假设这是窗体应用程序

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我试图通过 foreach 从选定的行中获取内容并执行 var 而不是 DataGridViewRow,对没有方法和所有内容感到有点生气,但它被视为对象。所以这段代码帮助了我。 VoteUp ;) 孩子们不会不假思索地做var!
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多