Donate

Custom DatagridviewCheckboxColumn In Windows Forms

Here's a simple class implementation of a DatagridviewCheckboxColumn.
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.
Custom DatagridviewCheckboxColumn In Windows Forms

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!

Comments

Post a Comment

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations