Search code examples
c#visual-studiodatagridviewnullreferenceexceptiondesigner

NullReferenceException when Designer assigns DataGridViewColumn HeaderText


Edit: Solution found. DataGridViewColumn HeaderText cells are defined as a row in the DataGridView. When they're changed, it calls a DataGridView.CellValueChangedevent.

So I have no idea what is causing this issue. My generated designer code is throwing a NullReferenceException for every time it sets the HeaderText of a column. The columns were created in the DataGridView properties. However, when I put in a quick try-catch to see what the HeaderText is, the name is correct. Here's one of the HeaderText assignments:

this.lightType.HeaderText = "Type";

Here's a quick code where I verified the HeaderText was correct after assignment (I'm not keeping this in the Designer code; just to debug).

try
   {
   this.lightType.HeaderText = "Type";
   }
catch(NullReferenceException e)
   {
   MessageBox.Show(e.Message);
   MessageBox.Show(lightType.HeaderText);
   }

The MessageBox and debugger both show the correct name directly after the assignment, but the assignment still throws a NullReferenceException.

Any ideas?


Solution

  • Apparently, the column names are defined as a row of the DataGridView, so when the names are changed, a DataGridView.CellValueChanged event is called, which I had a function for in my code that called then undeclared values.