Home > Software engineering >  Hiding particular datagridview cell in c#
Hiding particular datagridview cell in c#

Time:05-11

I have a datagridview in windows form. Datagridview looks like below:

enter image description here

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.

enter image description here

For this, I tried by two ways:

  1. 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.

  1. 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?

CodePudding user response:

Two steps.

  1. 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;
    }
}
  1. 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;
    }
}

CodePudding user response:

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;
    }
}
  • Related