Thursday, November 15, 2012

Custom DatagridviewCheckboxColumn

Here's a simple class implementation of a DatagridviewCheckboxColumn.
Code:
public class DatagridviewCustomCheckboxColumn : DataGridViewCheckBoxColumn   
   {   
     public DatagridviewCustomCheckboxColumn()   
     {   
      this.CellTemplate = new DatagridviewCheckboxCustomCell();   
    }   
   }   
   class DatagridviewCheckboxCustomCell : DataGridViewCheckBoxCell   
   {     
    public int row_index { get; set; }   
    public int CheckboxHeight    
    {   
     get   
     {   
      //your_desired_checkbox_height is a variable   
      //that contains the desired height of your checkbox   
      //you may set or get the property value..   
      return your_desired_checkbox_height;   
     }   
    }   
    public int CheckboxWidth    
    {   
     get   
     {   
      //your_desired_checkbox_width is a variable   
      //that contains the desired width of your checkbox   
      //you may set or get the property value..   
      return your_desired_checkbox_width;   
     }    
    }   
    /// <summary>   
    /// constructor   
    /// </summary>   
    public DatagridviewCheckboxCustomCell()   
    {   
    }   
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState,    
     object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle,    
     DataGridViewPaintParts paintParts)   
    {   
     base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);   
     this.row_index = rowIndex;   
     //create rectangle object then set    
     //the x,y,height,width based on your desired    
     //rectangle size...   
     Rectangle rect = new Rectangle();   
     if (value != null)   
     {   
      if ((bool)value)   
      {   
       graphics.FillRectangle(Brushes.Blue, rect);   
      }   
      else   
      {   
       graphics.FillRectangle(Brushes.Green, rect);   
      }   
     }   
    }   
   } 
The output resembles to the form shown below.

You may noticed that the last column in the datagridview shows a checkbox painted with colors rather than having checkmarks . True values are painted with blue while false values are painted with green. Cheers!

3 comments:

  1. Thanks Mr Greg. I've been looking for this for a long time now.

    ReplyDelete
  2. Excellent post, spot on for what I needed.

    ReplyDelete