Hi Programmers, I need to add the checkbox and label in the same cell.I do know how to do that. I can make the datagridviewcolumn to checkbox but then it only shows the checkbox and no place to show label. Can anybody wake me up from this nightmare? Thanks in advance.
I don't believe this is possible with the out of the box CheckBoxCell.
Here is an implementation which subclasses the check box column and does some custom painting to draw the label. It is possible to extend this in various ways, such as offering binding for the label text (it currently requires the label text being set directly). My code borrows heavily from this forum post.
using System;
using System.Windows.Forms;
using System.Drawing;
public class MyDGVCheckBoxColumn : DataGridViewCheckBoxColumn
{
private string label;
public string Label
{
get
{
return label;
}
set
{
label = value;
}
}
public override DataGridViewCell CellTemplate
{
get
{
return new MyDGVCheckBoxCell();
}
}
}
public class MyDGVCheckBoxCell : DataGridViewCheckBoxCell
{
private string label;
public string Label
{
get
{
return label;
}
set
{
label = value;
}
}
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)
{
// the base Paint implementation paints the check box
base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
// Get the check box bounds: they are the content bounds
Rectangle contentBounds = this.GetContentBounds(rowIndex);
// Compute the location where we want to paint the string.
Point stringLocation = new Point();
// Compute the Y.
// NOTE: the current logic does not take into account padding.
stringLocation.Y = cellBounds.Y + 2;
// Compute the X.
// Content bounds are computed relative to the cell bounds
// - not relative to the DataGridView control.
stringLocation.X = cellBounds.X + contentBounds.Right + 2;
// Paint the string.
if (this.Label == null)
{
MyDGVCheckBoxColumn col = (MyDGVCheckBoxColumn)this.OwningColumn;
this.label = col.Label;
}
graphics.DrawString(
this.Label, Control.DefaultFont, System.Drawing.Brushes.Red, stringLocation);
}
}
Here is code showing the usage:
private void Form1_Load(object sender, EventArgs e)
{
MyDGVCheckBoxColumn col = new MyDGVCheckBoxColumn();
col.Label = "hippo";
col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
this.dataGridView1.Columns.Add(col);
this.dataGridView1.RowCount = 5;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (row.Index % 2 == 0)
{
((MyDGVCheckBoxCell)row.Cells[0]).Label = "kitten";
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With