DataGridView行變色

效果直接在DataGridView的屬性中可以設置,選中記錄時的模式是選擇整行即可。

 

 

要求是選中的行變色,代碼如下

事件是RowPrePaint。

這個思路是先得到當前的行。RowPrePaint事件應該是每Paint一行之前的事件,所以對行進行檢查,如果滿足要求就設置成想要的樣式即可。因爲要把非當前行還原樣式,所以記錄了之前的顏色,估計直接記錄Style也是一種好方法。

  1.         void DataGridView1RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
  2.         {
  3.             if (e.RowIndex >= dataGridView1.Rows.Count - 1)
  4.                 return;
  5.             var row = (sender as DataGridView).Rows[e.RowIndex];
  6.             try
  7.             {
  8.                 Color oldForeColor = new Color();
  9.                 Color oldBackColor = new Color();
  10.                 if (row == (sender as DataGridView).CurrentRow) {
  11.                     if(row.DefaultCellStyle.ForeColor != Color.White)
  12.                     {
  13.                         oldForeColor = row.DefaultCellStyle.ForeColor;
  14.                         row.DefaultCellStyle.ForeColor = Color.White;
  15.                     }
  16.                     if(row.DefaultCellStyle.BackColor != Color.Blue)
  17.                     {
  18.                         oldBackColor = row.DefaultCellStyle.BackColor;
  19.                         row.DefaultCellStyle.BackColor = Color.Blue;
  20.                     }
  21.                 }
  22.                 else
  23.                 {
  24.                     row.DefaultCellStyle.ForeColor = oldForeColor;
  25.                     row.DefaultCellStyle.BackColor = oldBackColor;
  26.                 }
  27.             }
  28.             catch (Exception)
  29.             {
  30.             }
  31.         }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章