3

I want to add checkbox in a specific row and column but i'm always stumbled upon this error

"System.FormatException: Formatted value of the cell has a wrong type."

And here is my code to add the checkbox;

    private void checkboxSource(string columnSource, int n)
    {
        DataGridViewCheckBoxCell checkboxColumn = new DataGridViewCheckBoxCell();
        checkboxColumn.FalseValue = "0";
        checkboxColumn.TrueValue = "1";
        dataGridView1.Rows[n].Cells[6] = checkboxColumn;
    }

I know something is wrong when i try to bind checkboxColumn to datagridview. Can someone please guide me on how to bind the checkbox to datagridview properly provided which row and cell are taken into account. Thank you in advance.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
MRu
  • 1,225
  • 7
  • 20
  • 44

1 Answers1

1

The error is because the cell contains null value. You should set Style.NullValue of the cell to false. The property sets the display value when cell value is DBNull.Value or null:

var cell = new DataGridViewCheckBoxCell()
{
    TrueValue = "1",
    FalseValue = "0",
};
cell.Style.NullValue = false;
this.dataGridView1.Rows[2].Cells[0] = cell;
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Usually you should create a column of type `DataGridViewCheckBoxColumn` instead of changing the cell type. But if for some reason you need to change a specific cell type, you can change the cell type. – Reza Aghaei Jun 30 '16 at 02:41