VB.net数据库连接的空引用

TMB*_*B87 0 vb.net sql-server asp.net

我知道我在这里是个白痴,我无法解决这个问题.但我正试图从vb.net数据库中取回一些数据.它没有被设置为对象错误的实例,它正在倒下.在代码运行之前,它表示变量在设置之前正在使用,但我看不清楚如何.码:

  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
Run Code Online (Sandbox Code Playgroud)

它落在了 Dim forwardURL As String = notificationrow.ForwardLocation

Joe*_*ton 5

问题是你从未在if语句中实例化notificationRow.你已经声明了它,但它不属于任何东西.在对此对象执行任何操作之前,您需要进行赋值或遍历行:

Dim notificationrow As dsData.NotificationsRow ' this is not instantiated
Dim forwardURL As String = notificationrow.ForwardLocation
Run Code Online (Sandbox Code Playgroud)

在这种情况下你真正想要的是:

For Each notificationRow As dsData.NotificationRow In notification

    Dim forwardURL As String = notificationRow.ForwardLocation        
    ' Do Something

Next
Run Code Online (Sandbox Code Playgroud)

如果您只有一行并且您知道只有1行或0行,那么您可以通过执行以下操作来使用if语句:

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
Run Code Online (Sandbox Code Playgroud)

编辑:在上面的代码中,我原来只是notification.Rows(0).这将生成一个DataRow对象,但不会强类型化.您需要执行CType我添加的内容才能使用自定义属性ForwardLocation.