2012-06-13 47 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)