How to fix "nullreferenceexception" despite what's being referenced not being null?

0

Referring to Radio Button's using the below code to try to find the checked button keeps throwing NullReferenceException. I've tried referring to both it's .name and .tag properties, and they both worked on the first couple tries but then they started throwing NullReferenceExceptions, despite no changes to what they would be refernecing to.

On Visual Studio, tried changing to .name, as well as tried

    Dim strRBName As String = grpGrams.Controls.OfType(Of RadioButton).FirstOrDefault(Function(r) r.Checked = True).Name.ToString

I expected it to output the tag to use for some quick math, but when that threw out the exception I switched to it throwing out the .name to do some more annoying workaround until that started throwing the same exception.

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=Shopping Cart Project
  StackTrace:
   at Shopping_Cart_Project.Form1.ChangeDisplayedPrice(Object sender, EventArgs e) in C:\Users\Iyan D Barone\source\repos\Shopping Cart Solution\Shopping Cart Project\Form1.vb:line 62
   at System.Windows.Forms.RadioButton.OnCheckedChanged(EventArgs e)
   at System.Windows.Forms.RadioButton.set_Checked(Boolean value)
   at Shopping_Cart_Project.Form1.InitializeComponent() in C:\Users\Iyan D Barone\source\repos\Shopping Cart Solution\Shopping Cart Project\Form1.Designer.vb:line 180
   at Shopping_Cart_Project.Form1..ctor() in C:\Users\Iyan D Barone\source\repos\Shopping Cart Solution\Shopping Cart Project\Form1.vb:line 6
vb.net
asked on Stack Overflow Jun 13, 2019 by DannyDeVitoNA

1 Answer

0

To debug, try breaking it into more steps:

Dim rb As RadioButton = grpGrams.Controls.OfType(Of RadioButton).FirstOrDefault(Function(r) r.Checked = True)?.Name
Dim strRBName As String = Nothing
If rb IsNot Nothing Then strRBName = rb.Name

Check value of rb after first line. If it's null, which it will be if no controls are radio buttons or none are checked, then that's the issue. The above code would work, although this is a little more compact:

Dim strRBName As String = grpGrams.Controls.OfType(Of RadioButton).FirstOrDefault(Function(r) r.Checked = True)?.Name

Note the ? before .Name to cope with the Null value and Name already is a string so you don't need the ToString()

answered on Stack Overflow Jun 14, 2019 by Jon Roberts

User contributions licensed under CC BY-SA 3.0