2012-06-13 49 views
0

我知道我在这里是一个白痴,我只是不能解决它。但我试图从vb.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 

它在Dim forwardURL As String = notificationrow.ForwardLocation

回答

5

问题倒下的是,你从来没有实例化的if语句里面的notificationRow。你已经宣布了它,但它不属于任何东西。您需要与此对象做任何事情之前,使通过你的行转让或循环:

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

你真的想在这种情况下,什么是:

For Each notificationRow As dsData.NotificationRow In notification 

    Dim forwardURL As String = notificationRow.ForwardLocation   
    ' Do Something 

Next 

如果你只有一排,你知道你只有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 

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

+0

非常感谢!真的很有帮助 – TMB87

1

您从未将notificationrow设置为任何值。你是不是想这样设置?

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