Question

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.

Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"

Using dbContext As New EntitiesModel()
    Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
    mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using

----EDIT----

I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.

I get the same error, but at "Dim type = phonetype.First..." The record is in the table, but it does not appear to be extracted with my code.

Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
   mytextbox.Text = type.PhoneTypeName.ToString
End If
Was it helpful?

Solution 2

Fixed it.

I was able to view the SQL string being generated by using this: mytextbox.text = phonetype.tostring

I saw that the SQL contained "NULL= 'O'"

I did it like the example?!? However, when I added .ToString to the field being queried, it worked.

So the final looks like this:

Using dbContext As New EntitiesModel()
    Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
    mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using

BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

OTHER TIPS

In general there are the following two possible reasons for getting this exception:

1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.

2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.

In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:

Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
    mytextbox.Text = type.PhoneTypeName.ToString
End If
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top