C# – Convert a DataGridView Cell type at runtime

c++datagridviewwinforms

My datagridview has a checkbox column that is only valid for some records in the data it is displaying. For the records for which a checkbox is not valid I wish to display nothing – a blank textbox for example.

Thus i need to dynamically change the cell type at run time from a checkbox cell to a textbox cell. I cannot simply change the column data type as the column needs to have a mix of textbox and checkbox cell types.

So far I have the code below.

 this.deviceList1.DeviceGrid[colIndex, rowIndex] = new KryptonDataGridViewTextBoxCell()
 this.deviceList1.DeviceGrid[colIndex, rowIndex].ReadOnly = true;

Howver this generates a DataGridView data error:

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

Best Solution

Sorted it. Simple really. Solution is to ensure that the Value property is given an appropriate value. I.e it needs to be set to a string value.

this.deviceList1.DeviceGrid[colIndex, rowIndex] =  new KryptonDataGridViewTextBoxCell()
this.deviceList1.DeviceGrid[colIndex, rowIndex].ReadOnly = true;
this.deviceList1.DeviceGrid[colIndex, rowIndex].Value = "";