我有DataGridView
几列和几行数据。其中一列是 aDataGridViewCheckBoxColumn
和(基于行中的其他数据)我想要在某些行中“隐藏”复选框的选项。我知道如何使它只读,但我希望它根本不显示或至少显示与其他复选框不同(灰显)。这可能吗?
3 回答
一些解决方法:将其设为只读并将颜色更改为灰色。对于一个特定的单元格:
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);
}
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcell.aspx
DataGridViewCheckBoxCell.Visible = false;
编辑:哦,等等,它是只读的。德普。
在这种情况下,请尝试将单元格替换为空的 DataGridViewTextBoxCell。
取自Customize the Appearance of Cells in the Windows Forms DataGridView Control,如果单元格处于只读模式,您可以捕获 CellPainting 事件并且不绘制单元格。例如:
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();
唯一需要注意的是,当您更改ReadOnly
其中一个单元格的属性时,您需要调用DataGridViewCheckBox
。