2017-08-23 173 views
0

以下方法用於將所有行從窗體(form1的datagridview1)的數據網格視圖發送到另一個數據網格視圖窗體(form2的datagridview1)當單擊一個按鈕時。將數據從1個數據網格視圖發送到另一個數據網格視圖c#

 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!我如何糾正這一點?

+0

爲什麼不只是從一個數據源複製到另一個? – BugFinder

+0

@BugFinder我該怎麼做? –

+1

哇 - 我沒有意識到我有孩子,我需要做的一切..爲什麼不TRY – BugFinder

回答

0

根據不同的情況,我會與數據源的工作,即這樣

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 
相關問題