I have a DataGridView
with several columns and several rows of data. One of the columns is a DataGridViewCheckBoxColumn
and (based on the other data in the row) I would like the option to "hide" the checkbox in some rows. I know how to make it read only but I would prefer it to not show up at all or at least display differently (grayed out) than the other checkboxes. Is this possible?
C# DataGridViewCheckBoxColumn Hide/Gray-Out
15.4k Views Asked by john At
3
There are 3 best solutions below
0

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcell.aspx
DataGridViewCheckBoxCell.Visible = false;
Edit: Oh, wait, it's read only. Derp.
In which case, try replacing the cell with an empty DataGridViewTextBoxCell.
0

Taken from Customize the Appearance of Cells in the Windows Forms DataGridView Control, you could catch the CellPainting event and not draw the cell if its in read only mode. For example:
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;
}
}
}
}
The only caveat is that you need to call dataGridView1.Invalidate();
when you change the ReadOnly
property of one of the DataGridViewCheckBox
cell's.
Some workaround: make it read-only and change back color to gray. For one specific cell:
Or, better but more "complicated" solution:
suppose you have 2 columns: first with number, second with checkbox, that should not be visible when number > 2. You can handle
CellPainting
event, paint only borders (and eg. background) and break painting of rest. Add eventCellPainting
for DataGridView (optionally test for DBNull value to avoid exception when adding new data in empty row):It should work, however if you change value manually in first column, where you check condition, you must refresh the second cell, so add another event like
CellValueChanged
: