【问题标题】:how to pass values from datagridview1 in form1 to datagridview2 in form2?如何将值从form1中的datagridview1传递到form2中的datagridview2?
【发布时间】:2017-11-23 17:22:39
【问题描述】:

我必须将一些值从 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!");
}

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      试试这个:

      将 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 { }   }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-19
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多