Friday, 24 October 2008

Using RowPrePaint event of a DataGridView control

To draw a row in a DataGridView control in a different style depending on a certain condition, you can use the RowPrePaint event to interrupt the painting of the rows in the grid.

You then have a choice of which parts of the row to be painted automatically and which parts to paint yourself via the PaintParts event property.

In the code below, I paint a row with a custom brush, depending on the value of a column that is named 'Error'.

   1:  /// <summary>
   2:  /// Handles the drawing of each DataGridView row depending on set log error state.
   3:  /// </summary>
   4:  /// <param name="sender"></param>
   5:  /// <param name="e"></param>
   6:  private void setLogDataGridView_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
   7:  {
   8:      // Paint all parts of row except SelectionBackground and the Focus box.
   9:      e.PaintParts = DataGridViewPaintParts.All & ~(DataGridViewPaintParts.SelectionBackground | DataGridViewPaintParts.Focus);
  10:   
  11:      // Get the value of the error column of the current row
  12:      string val = this.setLogDataGridView.Rows[e.RowIndex].Cells["Error"].Value.ToString();
  13:   
  14:      if (val != "0")
  15:      {
  16:           // Get rectangle of area to paint with custom brush.
  17:            Rectangle rowBounds = new Rectangle(
  18:             this.setLogDataGridView.RowHeadersWidth, e.RowBounds.Top,
  19:             this.setLogDataGridView.Columns.GetColumnsWidth(
  20:             DataGridViewElementStates.Visible) -
  21:             this.setLogDataGridView.HorizontalScrollingOffset + 1,
  22:             e.RowBounds.Height);
  23:   
  24:      // Disable normal painting of backgrounds.
  25:      e.PaintParts &= ~(DataGridViewPaintParts.Background | DataGridViewPaintParts.ContentBackground);
  26:   
  27:      e.PaintHeader(false);
  28:   
  29:      // Paint the custom background.
  30:      using (Brush lgb = new LinearGradientBrush(rowBounds, Color.Red,
  31:             Color.DarkRed, LinearGradientMode.Vertical))
  32:      {
  33:          e.Graphics.FillRectangle(lgb, rowBounds);
  34:      }
  35:   
  36:      // Set the text colour.
  37:      this.setLogDataGridView.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Yellow;
  38:      this.setLogDataGridView.Rows[e.RowIndex].DefaultCellStyle.SelectionForeColor =      Color.Yellow;
  39:      }
  40:  }

0 comments: