【问题标题】:sending data from 1 data grid view to another data grid view in another form c#以另一种形式c#将数据从1个数据网格视图发送到另一个数据网格视图
【发布时间】:2017-08-23 09:35:00
【问题描述】:

当单击按钮时,我使用以下方法将所有行从表单中的数据网格视图(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();

}
            }

        }

但是没有数据发送到form2的datagridview1!我该如何纠正这个问题?

【问题讨论】:

  • 为什么不直接从一个数据源复制到另一个数据源?
  • @BugFinder 我该怎么做?
  • 因为你没有打电话给f2.Show() 我会粗略地假设你有错误的实例。单击button2 按钮时,您的Form2 是否已经打开?
  • @MongZhu not form2 目前已关闭
  • @MongZhu 在我放 f2.show() 后出现错误“int n = f2.dataGridView1.Rows.Add();”行

标签: c# button datagridview click


【解决方案1】:

根据情况,我会使用数据源,即这种方式

VB.NET

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

Me.DataGridView1.datasource = dt

Form2.DataGridView2.datasource = dt

C#

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

this.DataGridView1.datasource = dt;

Form2.DataGridView2.datasource = dt;

如果您想单独修改其中一个,则需要第二个数据表:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多