2014-01-18 36 views
0

我的datagridView1包含7列,第一個有日期。 我試圖從dataGridView1轉移月份數據dataGridView2 我曾嘗試使用一個循環,這在邏輯上認爲這是可行的,但它會給我nullExceptions試圖從一個dataGridView轉移到另一個

這裏是我的代碼:

for (int i = 0; i < f1.dataGrivView1.Rows.Count; i++) 
     { 
       if (f1.dataGrivView1.Rows[i].Cells[0].Value.ToString().Split('/')[1].StartsWith("01"))//if january.. 
       { 
        dataGrivView1.Rows.Add();//datagridview in current form 
        dataGrivView1.Rows[i].Cells[0].Value = f1.dataGrivView1.Rows[i].Cells[0].Value.ToString(); 
        dataGrivView1.Rows[i].Cells[1].Value = f1.dataGrivView1.Rows[i].Cells[1].Value.ToString(); 
        }} 

而且經過一些谷歌搜索之後,我發現你不能只用這種方式複製數據,你需要克隆它,所以我試了一下。

  foreach (DataGridViewRow dgvr in f1.dataGridView1.Rows) 
      { 
       DataGridViewRow r = dgvr.Clone() as DataGridViewRow; 
       foreach (DataGridViewCell cell in dgvr.Cells) 
       { 
        if (cell.Value.ToString().Contains("/01/")); 
        r.Cells[cell.ColumnIndex].Value = cell.Value; 
       } 

       dataGridView1.Rows.Add(r); 
      } 

但是..同樣的事情。 有什麼想法?

+0

日期爲dd/mm/yyyy形式,因此包含(/ 01 /)或startsWith(01)的作品。 – user3055826

+1

通過點擊一個按鈕,如果你想傳輸第一個網格數據到第二個網格,那麼我建議你保留兩個數據表並且使用可傳輸的數據表格並且網格將相應地刷新數據 –

+0

顯示如何在另一個表單中初始化'f1' 。我認爲你的'f1'爲空 – Fabio

回答

0

這確實將第一列值從DataGridView複製到另一列。

for(int i=0; i<f1.dataGridView1.Rows.Count; i++) 
    dataGridView1.Rows[i].Cells[0].Value = f1.dataGridView1.Rows[i].Cells[0].Value; 

拋出的任何異常都可能是由於新的dataGridView1在迭代中相應的索引處沒有現有行。

+0

我沒有將源dgv中的所有行克隆到新的dgv中,並且這樣做,它仍然給我一個空例外。 ._。 – user3055826

+1

如果您要複製的DataGridView具有要複製到的匹配行,上面的代碼將工作。否則,你可以給出確切的異常拋出。 – Spark

+0

NullReferenceException。我也從源dataGridView中複製沒有數據的行,所以它們幾乎是一樣的。 – user3055826

相關問題