将行从一个 DataGridView 复制到另一个 [英] Copying rows from one DataGridView to another

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

问题描述

我用C#写了一个连接SQL数据库的应用,有两种形式.

I have written an application that is connected to SQL database in C#.There are two forms.

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

I have a DataGrid in the first form. There are those columns like ID,AD,SOYAD in Datagridview.

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

I have a DataGrid in the second form(frm4) and there are those columns like ID,AD,SOYAD in Datagridview.

我将 ContextMenuStrip 放在第一个 DataGridView 中.

I put ContextMenuStrip in the first DataGridView.

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

My question is:I want to add to second DataGridView those rows which are choosen in the first 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();

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

I only can add one row with upper code. But,I want to add multiple rows. I'm using below code for that. But, it's not working.

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

推荐答案

假设这是windows窗体应用程序

assume this is windows form application

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 复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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