Setting DataGridView.DefaultCellStyle.NullValue to null at designtime raises error at adding rows runtime

StackOverflow https://stackoverflow.com/questions/48271

  •  09-06-2019
  •  | 
  •  

Question

In Visual Studio 2008

  • add a new DataGridView to a form
  • Edit Columns
  • Add a a new DataGridViewImageColumn
  • Open the CellStyle Builder of this column (DefaultCellStyle property)
  • Change the NullValue from System.Drawing.Bitmap to null
  • Try to add a new Row to the DataGridView at runtime (dataGridView1.Rows.Add();)
  • You get this error: System.FormatException: Formatted value of the cell has a wrong type.

If you change back the NullValue to System.Drawing.Bitmap (as it was) you still get the same error at adding a row.

If you set the NullValue at runtime instead of designtime you don't get anny error. (dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;)

Could you tell me why is that?

Was it helpful?

Solution

This may well be a bug in the designer; if you take a look around at the .designer.cs file (maybe doing a diff from before and after you set NullValue to null) you should be able to see the code it generates.

OTHER TIPS

Kronoz is right. After setting it at designtime it adds this to the .designer.cs:

dataGridViewCellStyle1.NullValue = "null";

If I modify "null" to null then it works fine. I checked the DataGridViewCellStyle.NullValue set_NullValue(Object) and get_NullValue with reflector and I think that a string value shouldn't raise any error here.

Anyway be careful with this and if you want to set it designtime then don't forget to modify the .design.cs.

Change the NullValue from System.Drawing.Bitmap to null

When you enter 'null' into the field for NullValue in the Designer, you are specifing the string value "null". The only way to set NullValue to a non-string value is to set it programmatically or by modifing the designer code yourself.

Checkbox can't have a String value. Don't set any default value in the IDE properties dialog. I had "Empty" written into the RowsDefaultCellStyle.Format property and that caused the error. It was self inflicted. As a fix I was trying to set the checkbox state to unchecked but I just needed to delete the string value.

I found that its better if you just delete the item from the designer all together from the Format area and the default null value area. Then it sets it back to the real null. I'm going to try to set it in the init section away from the designer generated crap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top