2014-10-10 142 views
1

我正面臨有關DataGridView單元格背色的問題。如何重新設置或刷新DataGridView Cell的背景顏色?

首先我改變datagridview2的特定單元格的背景顏色。

int cnt = dataGridView1.Rows.Count; 
     for (int i = 0; i < cnt; i++) 
     { 
      string starting = dataGridView1.Rows[i].Cells[9].Value.ToString(); 
      string startings = Convert.ToDateTime(starting.ToString()).ToString("dd MMM yyyy"); 
      string ending = dataGridView1.Rows[i].Cells[10].Value.ToString(); 
      string endings = Convert.ToDateTime(ending.ToString()).ToString("dd MMM yyyy"); 

      TimeSpan ts = Convert.ToDateTime(ending.ToString()) - Convert.ToDateTime(starting.ToString()); 
      double diff = ts.TotalDays + 1; 
      int dif = Convert.ToInt32(diff); 
      for (int d = 0; d < dif; d++) 
      { 
       string str = Convert.ToDateTime(starting.ToString()).AddDays(d).ToString("dd MMM yyyy"); 
       dataGridView2.Rows[i].Cells[str].Style.BackColor = Color.Olive; 
      } 
     }  

我需要根據在datagridview1中輸入的新值重置背景顏色。這是我的代碼。

Private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.ColumnIndex == 7 || e.ColumnIndex == 8 || e.ColumnIndex == 9 || e.ColumnIndex == 10) 
     { 
      int prd_per_d = Convert.ToInt32(dataGridView1.CurrentRow.Cells[7].Value); 
      int qty=Convert.ToInt32(dataGridView1.CurrentRow.Cells[6].Value); 
      dataGridView1.CurrentRow.Cells[8].Value = qty/prd_per_d + 5; 

      DateTime sdt = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[9].Value); 
      int req_day = Convert.ToInt32(dataGridView1.CurrentRow.Cells[8].Value); 
      dataGridView1.CurrentRow.Cells[10].Value = sdt.AddDays(req_day); 

      int cnt = dataGridView1.Rows.Count; 
      for (int i = 0; i < cnt; i++) 
      { 
       string starting = dataGridView1.Rows[i].Cells[9].Value.ToString(); 
       string startings = Convert.ToDateTime(starting.ToString()).ToString("dd MMM yyyy"); 
       string ending = dataGridView1.Rows[i].Cells[10].Value.ToString(); 
       string endings = Convert.ToDateTime(ending.ToString()).ToString("dd MMM yyyy"); 

       TimeSpan ts = Convert.ToDateTime(ending.ToString()) - Convert.ToDateTime(starting.ToString()); 
       double diff = ts.TotalDays + 1; 
       int dif = Convert.ToInt32(diff); 

       for (int d = 0; d < dif; d++) 
       { 
        string str = Convert.ToDateTime(starting.ToString()).AddDays(d).ToString("dd MMM yyyy"); 

        dataGridView2.Rows[i].Cells[str].Style.BackColor = Color.Olive; 
       } 
      } 

     } 
    }  

但是,當我在datagridview1中輸入值時,沒有可見的變化發生。它僅適用於新的單元格,但不會將現有的彩色單元格更改爲默認單元格。 有什麼想法爲什麼?

+0

嗯,所以你錯過了'CellEndEdit'事件的ui更新,對不對?它可能會限制自己刷新編輯的單元格。也許你應該在最後添加一個DGV.Refresh調用? – TaW 2014-10-10 14:39:32

+0

沒有變化.. – Bappy 2014-10-11 03:30:41

+0

嗯,你確定那些細胞/列名嗎?我懷疑他們可以在他們的空間..!儘管如此,應該拋出異常 – TaW 2014-10-11 18:48:04

回答

0

我在一週前得到了同樣的問題。我用兩行程序代碼解決了它。希望這會幫助你! :

 this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; 
     this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;