0

I know I'm being an idiot here and I just can't work it out. But i'm trying to take some data back from a vb.net database. It's falling over with a Object reference not set to an instance of an object error. And before the code runs it's saying the variable is being used before it's set, but I can't see how. Code:

  Private taNotifications As dsDataTableAdapters.NotificationsTableAdapter = New dsDataTableAdapters.NotificationsTableAdapter 

   Dim notification As dsData.NotificationsDataTable = taNotifications.GetDataByClientID(userrow.UserID)

                If notification.Rows.Count > 0 Then

                    Dim notificationrow As dsData.NotificationsRow
                    Dim forwardURL As String = notificationrow.ForwardLocation

                End If

It falls over on the Dim forwardURL As String = notificationrow.ForwardLocation

2 Answers 2

5

The problem is that you have never instantiated the notificationRow inside the if statement. You've declared it, but it doesn't belong to anything. You need to make an assignment or loop through your rows before doing anything with this object:

Dim notificationrow As dsData.NotificationsRow ' this is not instantiated
Dim forwardURL As String = notificationrow.ForwardLocation

What you really want in this case is:

For Each notificationRow As dsData.NotificationRow In notification

    Dim forwardURL As String = notificationRow.ForwardLocation        
    ' Do Something

Next

If you only HAVE one row and you know you only have 1 or 0 rows then you could use your if statement by doing:

If notification.Rows.Count > 0 Then

    Dim notificationrow As dsData.NotificationsRow = _
        CType(notification.Rows(0), dsData.NotificationsRow)

    Dim forwardURL As String = notificationrow.ForwardLocation

End If

Edit: In the code above, I originally just had notification.Rows(0). This will produce a DataRow object, but it will not be strongly typed. You need to perform the CType that I added in order to use the custom property ForwardLocation.

Sign up to request clarification or add additional context in comments.

Comments

1

You never set notificationrow to anything. Did you mean to set it like this?

Dim notificationrow As dsData.NotificationsRow = CType(notification.Rows(0), dsData.NotificationsRow)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.