Csharp/C#教程:将行从一个DataGridView复制到另一个DataGridView分享


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

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

我有第一种forms的DataGrid。 Datagridview中有ID,AD,SOYAD等列。

我有第二种forms的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(); } 

假设这是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(); ..... } } 

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

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

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

上述就是C#学习教程:将行从一个DataGridView复制到另一个DataGridView分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/989948.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐