如何将form1中datagridview1的值传递给form2中的datagridview2?

时间:2014-12-11 15:32:43

标签: c# winforms datagridview

我必须将dataGridView1中的一些值传递给另一个表单的dataGridView ...

我正在使用DataTable来填充所有这些值...

这是我在form1中的数据表:

{
    table = new DataTable();

    table.Columns.Add("ID", typeof(int));
    table.Columns.Add("ItemCode", typeof(string));
    table.Columns.Add("ProductName", typeof(string));
    table.Columns.Add("Amount", typeof(string));
    table.Columns.Add("Quantity", typeof(string));
}
table.Rows.Add(ID, ItemCode, ProductName, Total,qty);
dataGridView2.DataSource = table;

我需要将这些值填充到form2中的另一个dataGridView中。

所有这一切都应该通过按钮点击事件发生......

这是对象引用问题的开始......

if (dataGridView2.RowCount != 0)
{        
    foreach (DataGridViewRow row in dataGridView2.Rows)        
    {                                                   
        ((Form2)f).dataGridView1.Rows.Add(row);
    }
}
else
{
    MessageBox.Show("Ordered Item list is Empty!");
}

最后我用这个解决了它

if (dataGridView2.RowCount != 0)
{
    foreach (DataGridViewRow row in dataGridView2.Rows)
    {
        if (row.IsNewRow) continue;
        {
            object[] rowData = new object[row.Cells.Count];
            for (int i = 0; i < rowData.Length; ++i)
            {
                rowData[i] = row.Cells[i].Value;
            }
            dataGridView1.Rows.Add(rowData);
        }
    }
}
else
{
    MessageBox.Show("Ordered Item list is Empty!");
}

2 个答案:

答案 0 :(得分:1)

快速搜索会产生几个可能对您的情况有用的帖子。我认为这个特别有用:

How to copy/transfer values from form2 datagridview to form1 datagridview in c#

你想要反过来,但想法是一样的。 Form1应该引用Form2。然后,您可以将Form2中的datagridview设置为public,也可以提供一个公共方法,允许Form1在Form1按钮单击事件中对其进行更改。

答案 1 :(得分:0)

试试这个:

将Form1的DGV声明为Public而不是private,并在Form2中执行以下操作:

声明以下变量:

System.Windows.Forms.Form f = System.Windows.Forms.Application.OpenForms["Form1"];.
Do the Following changes in your program:
 private void button1_Click (object sender, EventArgs e)      
 {

 try
  {
    if (dataGridView1.RowCount != 0)
    {

        foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {                                       
            ((Form1)f).dataGridView1.Rows.Add(row);                    
        }

      }
    else
    {
        MessageBox.Show("There is no data to export, please verify..!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
catch { }   }
相关问题