【问题标题】:How to hide CheckBox in DataGridView if value of cell is null如果单元格的值为空,如何在 DataGridView 中隐藏 CheckBox
【发布时间】:2019-08-22 08:28:27
【问题描述】:
我有从包含bit 列的表中填充DataGridView 的Winform。
如果值为null,我需要隐藏CheckBox,如果值为true 或false,则保持可见。
如果单元格的值为null,我如何在DataGridView 中隐藏CheckBox?
【问题讨论】:
标签:
c#
.net
winforms
datagridview
【解决方案1】:
处理CellPainting事件,如果单元格的值为null或DBNnull.Value,则不要绘制复选框:
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 1 &&
(e.Value == DBNull.Value || e.Value == null))
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.All &
~DataGridViewPaintParts.ContentForeground);
e.Handled = true;
}
}
注意:
-
e.RowIndex >= 0 确保我们渲染的是数据单元格,而不是标题单元格。
-
e.ColumnIndex == 1 确保我们在索引 1 处应用列的逻辑。如果您想要另一列的逻辑,请使用 فhat 列的索引。
-
e.Paint(...); 正在绘制单元格的所有部分,除了作为复选框的单元格内容前景。
-
e.Handled = true; 将绘画设置为已处理,因此默认的绘画逻辑不会运行。
- 它不会将单元格设为只读。它只是跳过渲染复选框。
- 不要忘记将事件处理程序添加到事件中。