'Hiding particular datagridview cell in c#
I have a datagridview in windows form. Datagridview looks like below:
In this, have one Checkbox column, two textbox column.
My requirement is need to hide checkbox from the cell for the country has Germany as like below.
For this, I tried by two ways:
By setting visible property as false.
datagridview.Rows[rowIndex].Cells[columnIndex].visible = false;
When using visible property, it showing error like cannot assigned to readonly.
Trying by converting the type of datagridview cell from checkbox to textbox for the particular cell.
DataGridViewTextBoxCell textBoxCell = new DataGridViewTextBoxCell();
datagridview.Rows[rowIndex].Cells[columnIndex] = textBoxCell;
For this, I am getting error like "Formatted value of the cell has a wrong type".
Is anyone have idea for this?
Solution 1:[1]
A good solution is handling CellPaint event and not to draw the cell content, but just background and borders:
void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//Check if the cell is one of those in which you are interested
if (e.ColumnIndex == 0 && e.RowIndex == 2)
{
//Prevent default paint
e.Handled = true;
var selected = (e.State & DataGridViewElementStates.Selected) != 0;
e.PaintBackground(e.CellBounds, selected);
}
}
You may also want to prevent cell editing, by setting it as RaedOnly or handling the CellBeginEdit:
void DataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
//Check if the cell is one of those in which you are interested
if (e.ColumnIndex == 0 && e.RowIndex == 2)
{
//Prevent entering to edit mode
e.Cancel = true;
}
}
Solution 2:[2]
- Handle
CellPainting
and don't render the check box
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex == [index] && e.RowIndex == dataGridView1.NewRowIndex)
{
e.PaintBackground(e.ClipBounds, true);
e.Handled = true;
}
}
- Handle
CellContentClick
and check if the cell don't do anything. This might not be needed.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == [index] && e.RowIndex >= 0 && e.RowIndex!=dataGridView1.newRowIndex)
{
return false;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |