我有一个包含几列和几行数据的 DataGridView
。其中一列是 DataGridViewCheckBoxColumn
并且(基于行中的其他数据)我希望选择“隐藏”某些行中的复选框。我知道如何使它只读,但我希望它根本不显示,或者至少显示与其他复选框不同(变灰)。这可能吗?
最佳答案
一些解决方法:将其设为只读并将背景颜色更改为灰色。
对于一个特定的单元格:
dataGridView1.Rows[2].Cells[1].Style.BackColor = Color.LightGray;
dataGridView1.Rows[2].Cells[1].ReadOnly = true;
或者,更好但更“复杂”的解决方案:
假设您有 2 列:第一列是数字,第二列是复选框,当数字 > 2 时不可见。您可以处理
CellPainting
事件,仅绘制边框(例如背景)并中断其余部分的绘制。为 DataGridView 添加事件 CellPainting
(可选地测试 DBNull 值以避免在空行中添加新数据时出现异常):private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//check only for cells of second column, except header
if ((e.ColumnIndex == 1) && (e.RowIndex > -1))
{
//make sure not a null value
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != DBNull.Value)
{
//put condition when not to paint checkbox
if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value) > 2)
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.Border | DataGridViewPaintParts.Background); //put what to draw
e.Handled = true; //skip rest of painting event
}
}
}
}
它应该可以工作,但是如果您在检查条件的第一列中手动更改值,则必须刷新第二个单元格,因此添加另一个事件,如
CellValueChanged
:private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
dataGridView1.InvalidateCell(1, e.RowIndex);
}
}
关于C# DataGridViewCheckBoxColumn 隐藏/灰显,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7664115/