嗨程序员, 我需要在同一个单元格中添加复选框和标签。我知道如何做到这一点。我可以将datagridviewcolumn设置为复选框,但它只显示复选框,没有显示标签的位置。有人能从这场噩梦中叫醒我吗? 提前谢谢。
答案 0 :(得分:5)
我不相信开箱即用的CheckBoxCell可以实现这一点。
这是一个实现,它对复选框列进行子类化,并执行一些自定义绘制以绘制标签。可以通过各种方式扩展它,例如为标签文本提供绑定(它当前需要直接设置标签文本)。我的代码大量借鉴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);
}
}
以下是显示用法的代码:
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";
}
}
}