2015-01-20 57 views
0

我正在創建一個程序,該程序使用DataGridView編輯SQL數據庫中的記錄。我的項目經理要求行按綠色,黃色或紅色進行着色,具體取決於它們是否已在時間窗口內插入,更新或標記爲刪除。他還希望使用該列對DataGridView彩色淺灰色進行分類。爲了解決這個問題,我創建了以下事件處理程序我的表單中:在DataGridView的列之前着色行

private void OnRowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) 
    { 
     //get the row 
     DataRow row = ((DataRowView)this.dataGridView.Rows[e.RowIndex].DataBoundItem).Row; 

     //color the row 
     try 
     { 
      //REDACTED 
      //gets booleans used below 
      //REDACTED 

      if (softDeleted) 
       this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 213, 91, 95); //red 
      else if (inserted) 
       this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 83, 223, 146); //green 
      else if (updated) 
       this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 234, 218, 106); //yellow 
      else 
       this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Empty; 
     } 
     //on failure, abort coloring 
     catch(Exception ex) 
     { 
      MessageBox.Show("Unable to get data required for coloring - " + ex.Message + ".\n Coloring disabled."); 
      Logging.logException(ex); 
      this.dataGridView.RowPrePaint -= OnRowPrePaint; 
     } 
    } 
    private void OnSorted(object sender, EventArgs e) 
    { 
     //remove color from previous sort column and add to new 
     if (this.mLastSortColumnIndex != -1) 
     { 
      this.dataGridView.Columns[this.mLastSortColumnIndex].DefaultCellStyle.BackColor = Color.Empty; 
     } 
     this.mLastSortColumnIndex = this.dataGridView.SortedColumn.Index; 
     this.dataGridView.SortedColumn.DefaultCellStyle.BackColor = Color.LightGray; 
    } 

這個奇妙的作品,我用它太開心了!或者,直到我的項目經理堅持認爲排序顏色(列着色)覆蓋了行着色。我的所有嘗試都遇到了失敗 - 有什麼辦法可以徹底解決這個問題嗎?

以下圖示 - 左側電流,右側需要。 Illustration

回答

1

附加處理程序CellPainting事件

void OnGridCellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.RowIndex >= 0 && e.ColumnIndex == mLastSortColumnIndex) 
     e.CellStyle.BackColor = Color.LightGray; 
} 

此方法設置淺灰色的顏色在排序列單元格RowPrePaint

+0

後,我不知道我是多麼懷念這種情況下尋找可能的解決方法的API時。 .. 奇蹟般有效;謝謝! – Conduit 2015-01-20 20:06:43