简体   繁体   English

以另一种形式将数据从一个数据网格视图发送到另一个数据网格视图

[英]sending data from 1 data grid view to another data grid view in another form c#

The following method is used by me to send all rows from a data grid view in a form(datagridview1 of form1) to another data grid view of another form(datagridview1 of form2) when a button is clicked. 我使用以下方法,以在单击按钮时将所有行从表单(form1的datagridview1)中的数据网格视图发送到另一表单(form2的datagridview1)的另一个数据网格视图。

     private void button2_Click(object sender, EventArgs e)
        {
           Form2 f2 = new Form2();
            DataTable dt1 = new DataTable();
            f2.dataGridView1.DataSource = dt1;

            foreach (DataGridView row in dataGridView1.Rows)
            {
                int n = f2.dataGridView1.Rows.Add();
                foreach (DataGridViewColumn col in dataGridView1.Columns)
                {
                    f2.dataGridView1.Rows[n].Cells[col.Index].Value = dataGridView1.Rows[row.Index].Cells[col.Index].Value.ToString();

}
            }

        }

But no data is sent to datagridview1 of form2! 但是没有数据发送到form2的datagridview1! how can i correct this? 我该如何纠正?

Depending on the circumstances, I'd work with a data source, ie this way 根据情况,我将使用数据源,即这种方式

VB.NET VB.NET

Dim dt as New DataTable
dt = ds.Tables(0)

Me.DataGridView1.datasource = dt

Form2.DataGridView2.datasource = dt

C# C#

DataTable dt = new DataTable();
dt = ds.Tables(0);

this.DataGridView1.datasource = dt;

Form2.DataGridView2.datasource = dt;

If you wanted to modify one of them independently, you need a second datatatable: 如果要独立修改其中之一,则需要第二个数据:

Dim dt2 as New DataTable
dt2 = dt.Copy()   ' copies datatable structure AND the data
Form2.DataGridView2.datasource = dt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM