MRu
MRu

Reputation: 1395

How to add checkbox at specific row and column?

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.

Upvotes: 3

Views: 3537

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

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;

Upvotes: 1

Related Questions