NullReferenceException Problem

dpdmembers
dpdmembers used Ask the Experts™
on
I am retrieving some data form a table using linq.  I am pulling that info into text boxes I have on a form.  But because some of the fields may be null and there is no way to know which ones will be null at any given time, thus I keep getting a NullReferenceException or an Object reference not set to an instance of an object error.  I have tried everything to try to test the field to see if it is null but nothing has work.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
can you show us some code for which you have issues?

are you using VS2015 and targeting one of the last Framework? If yes, you might want to try the Elvis operator: https://msdn.microsoft.com/en-us/library/dn986595.aspx

Author

Commented:
I am using VS2012.

 Dim xNo = (From xReg In _Context.tbl_Peoples
                          Where xReg.str_Nat = Me.NatTextBox.Text
                          Select xReg)

If xNo.Count > 0 Then
            For Each NatReg In xNo

                NameTextBox.Text = NatReg.str_ForeName2

            Next

End If


If NatReg.str_ForeName2 is null in the database table I get the errors.
Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
can you try:
if string.isnullorwhitespace(NatReg.str_ForeName2) then
   NameTextBox.Text = string.empty
else
   NameTextBox.Text = NatReg.str_ForeName2
end if

Open in new window

Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Author

Commented:
I tried that already.  Does not even get past the IF.

I got the error Object reference not set to an instance of an object.

Author

Commented:
attached file For your review
capture.png
Senior .Net Consultant
Top Expert 2016
Commented:
that means that your NatReg is empty:

if NatReg is nothing orelse  string.isnullorwhitespace(NatReg.str_ForeName2) then
   NameTextBox.Text = string.empty
else
   NameTextBox.Text = NatReg.str_ForeName2
end if

Open in new window

Author

Commented:
Looks promising..will test it over the weekend and get back to you.  Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial