C# DataGridViewButtonColumn充当DataGridViewCheckBoxColumn
我想让C# DataGridViewButtonColumn充当DataGridViewCheckBoxColumn,c#,.net,winforms,datagridview,datagridviewcolumn,C#,.net,Winforms,Datagridview,Datagridviewcolumn,我想让DataGridViewButtonColumn充当DataGridViewCheckBoxColumn。这意味着按钮中的某个图像为true,另一个图像为false,并通过DataMember绑定到属性。 我认为继承自DataGridViewCheckBoxColumn和重写paint方法的类“应该”工作。只需使用DataGridViewCheckBoxColumn但处理DataGridView的CellPaint事件,并为选中状态绘制一个图像,为未选中状态绘制另一个图像 示例 创建名为F
DataGridViewButtonColumn
充当DataGridViewCheckBoxColumn
。这意味着按钮中的某个图像为true
,另一个图像为false
,并通过DataMember
绑定到属性。
我认为继承自
DataGridViewCheckBoxColumn
和重写paint
方法的类“应该”工作。只需使用DataGridViewCheckBoxColumn
但处理DataGridView
的CellPaint
事件,并为选中状态绘制一个图像,为未选中状态绘制另一个图像
示例
创建名为Form1
的表单
,然后在表单上放置DataGridView
控件,并用以下代码替换Form1.cs
的内容。还要确保已将选中的
和未选中的
图像添加到资源
然后你会看到这样的结果:
那么你的问题是什么?你试过什么了?到目前为止,我还停留在绘画方法上。不知道该怎么办不需要继承任何东西。只需使用网格的CellPainting事件。@ihisham您是否尝试了解如何在winforms中绘制图像?快速问题我将代码移动到独立的DataGridViewColumn,以便可以自由使用它。它正在工作,但是当我处于编辑模式时,我没有得到视觉更新,更新只有在我退出时才生效。知道为什么吗?你确定你是从DataGridViewCheckBoxColumn
派生的吗?嗯,也许发布一个包含您创建的自定义列代码的新问题会更好
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
this.dataGridView1.CellPainting += dataGridView1_CellPainting;
}
private void Form1_Load(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Column1", typeof(bool));
dt.Rows.Add(false);
dt.Rows.Add(true);
this.dataGridView1.DataSource = dt;
}
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex >= 0)
{
var value = (bool?)e.FormattedValue;
e.Paint(e.CellBounds, DataGridViewPaintParts.All &
~DataGridViewPaintParts.ContentForeground);
var img = value.HasValue && value.Value ?
Properties.Resources.Checked : Properties.Resources.UnChecked;
var size = img.Size;
var location = new Point((e.CellBounds.Width - size.Width) / 2,
(e.CellBounds.Height - size.Height) / 2);
location.Offset(e.CellBounds.Location);
e.Graphics.DrawImage(img, location);
e.Handled = true;
}
}