C#DataGridViewCheckBoxColumn隐藏/灰显
我有一个C#DataGridViewCheckBoxColumn隐藏/灰显,c#,datagridview,datagridviewcheckboxcell,C#,Datagridview,Datagridviewcheckboxcell,我有一个DataGridView,其中有几列和几行数据。其中一列是DataGridViewCheckBoxColumn,并且(基于行中的其他数据)我希望选项“隐藏”某些行中的复选框。我知道如何使其只读,但我更希望它不显示在所有或至少显示不同的(灰色)比其他复选框。这可能吗? 编辑:哦,等等,它是只读的。德普 在这种情况下,请尝试使用空的DataGridViewTextBoxCell替换单元格。一些解决方法:将其设置为只读,并将返回颜色更改为灰色。 对于一个特定单元: dataGridView1.
DataGridView
,其中有几列和几行数据。其中一列是DataGridViewCheckBoxColumn
,并且(基于行中的其他数据)我希望选项“隐藏”某些行中的复选框。我知道如何使其只读,但我更希望它不显示在所有或至少显示不同的(灰色)比其他复选框。这可能吗?
编辑:哦,等等,它是只读的。德普
在这种情况下,请尝试使用空的DataGridViewTextBoxCell替换单元格。一些解决方法:将其设置为只读,并将返回颜色更改为灰色。 对于一个特定单元:
dataGridView1.Rows[2].Cells[1].Style.BackColor = Color.LightGray;
dataGridView1.Rows[2].Cells[1].ReadOnly = true;
或者,更好但更“复杂”的解决方案:假设您有两列:第一列带有数字,第二列带有复选框,当数字>2时,该列不应可见。您可以处理
CellPainting
事件,只绘制边框(如背景)并中断其余部分的绘制。为DataGridView添加事件CellPaint
(可选测试DBNull值,以避免在空行中添加新数据时出现异常):
但是,如果您手动更改第一列中的值(检查条件),则必须刷新第二个单元格,因此添加另一个事件,如CellValueChanged
:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
dataGridView1.InvalidateCell(1, e.RowIndex);
}
}
如果单元格处于只读模式,则可以捕获单元格绘制事件,而不绘制单元格。例如:
public Form1()
{
InitializeComponent();
dataGridView1.CellPainting += new
DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
}
private void dataGridView1_CellPainting(object sender,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
// Change 2 to be your checkbox column #
if (this.dataGridView1.Columns[2].Index == e.ColumnIndex && e.RowIndex >= 0)
{
// If its read only, dont draw it
if (dataGridView1[e.ColumnIndex, e.RowIndex].ReadOnly)
{
// You can change e.CellStyle.BackColor to Color.Gray for example
using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
// Erase the cell.
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Handled = true;
}
}
}
}
唯一需要注意的是,您需要调用dataGridView1.Invalidate()当您更改其中一个DataGridViewCheckBox
单元格的ReadOnly
属性时,代码>
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
dataGridView1.InvalidateCell(1, e.RowIndex);
}
}
public Form1()
{
InitializeComponent();
dataGridView1.CellPainting += new
DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting);
}
private void dataGridView1_CellPainting(object sender,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
// Change 2 to be your checkbox column #
if (this.dataGridView1.Columns[2].Index == e.ColumnIndex && e.RowIndex >= 0)
{
// If its read only, dont draw it
if (dataGridView1[e.ColumnIndex, e.RowIndex].ReadOnly)
{
// You can change e.CellStyle.BackColor to Color.Gray for example
using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
// Erase the cell.
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
e.Handled = true;
}
}
}
}