joh*_*ohn 4 c# datagridview datagridviewcheckboxcell
我有DataGridView几列和几行数据.其中一列是a DataGridViewCheckBoxColumn和(根据行中的其他数据)我希望选择"隐藏"某些行中的复选框.我知道如何让它只读,但我更希望它不显示或至少显示不同(灰显)比其他复选框.这可能吗?
mj8*_*j82 12
一些解决方法:将其设置为只读并将颜色更改为灰色.对于一个特定的细胞:
dataGridView1.Rows[2].Cells[1].Style.BackColor = Color.LightGray;
dataGridView1.Rows[2].Cells[1].ReadOnly = true;
Run Code Online (Sandbox Code Playgroud)
或者,更好但更"复杂"的解决方案:
假设你有两列:第一列是数字,第二列是复选框,当数字> 2时,它不应该是可见的.你可以处理CellPainting事件,只绘制边框(例如背景)并打破绘画的休息.CellPainting为DataGridView 添加事件(可选择测试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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它应该工作,但是如果您在第一列中手动更改值,在那里检查条件,则必须刷新第二个单元格,因此添加另一个事件,如CellValueChanged:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)
{
dataGridView1.InvalidateCell(1, e.RowIndex);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13265 次 |
| 最近记录: |