Tuesday, October 8, 2013

CheckBoxList control with multi-highlighting support (C#)

If you want to customize the CheckBoxList control to support multi-highlighting (each checked item is highlighted), you can simply override the OnDrawItem() by adding Graphics statements as shown below:
Here's an image sample of the extended CheckBoxList control:
     protected override void OnDrawItem(DrawItemEventArgs e)  
       int index = e.Index;  
                if (this.GetItemCheckState(index) == CheckState.Checked)  
                     string text = this.Items[index].ToString();  
                     Graphics g = e.Graphics;  
                     Point point = this.GetItemRectangle(index).Location;  
                     point.X += estimated_point; //estimated point is a value you may set manually  
                     SolidBrush backgroundBrush;            
                     backgroundBrush = reportsBackgroundBrushSelected;  
                     //estimated point is a value you may set manually  
                     g.FillRectangle(backgroundBrush, estimated_point , e.Bounds.Y, this.Width, e.Bounds.Height);  
                     SolidBrush foregroundBrush = reportsForegroundBrushSelected;  
                     g.DrawString(text, e.Font, foregroundBrush, point);