2013-04-11 43 views
1

我有一個SQL DB與表(Beko),其中每個記錄包含日期戳(數據類型日期)爲其創建日期。我試圖填充日曆控件(calBeko),以便突出顯示存在記錄的每一天。VB - System.NullReferenceException - LINQ to SQL與日期戳

我宣佈我的頁面類下面來保存包含記錄中的天

Private days As IEnumerable(Of DateTime) = Nothing 

然後我使用的Page_PreRender事件下面的創建和包含記錄的天陣:

Dim startDate, endDate, baseDate As DateTime 

    If calBeko.VisibleDate.Year <> 1 Then 
     baseDate = calBeko.VisibleDate 
    Else 
     baseDate = DateTime.Now 
    End If 

    startDate = New DateTime(baseDate.Year, baseDate.Month, 1) 
    endDate = startDate.AddMonths(1).AddDays(-1) 

    Dim dc As New BekoDataContext 
    Dim days = (From Beko In dc.Bekos _ 
       Where Beko.DateStamp <= endDate And _ 
       Beko.DateStamp >= startDate _ 
       Order By Beko.DateStamp _ 
       Select New DateTime(Beko.DateStamp.Year, _ 
            Beko.DateStamp.Month, _ 
            Beko.DateStamp.Day) Distinct).ToArray() 

然後我用calBeko_DayRender活動,強調其中一個記錄存在的天數:

For Each d In days 
     If d.Day = e.Day.Date.Day AndAlso _ 
      d.Month = e.Day.Date.Month Then 
      e.Cell.CssClass = "ajax_calendar_checkday" 
      Exit For 
     End If 
    Next 

問題是,當我跑,我在下面的行得到一個System.NullReferenceException頁:

For Each d In days 

似乎沒有值被分配到「天」。我已經檢查過表格,並且在那裏有有效的記錄,所以我假設我的代碼是錯誤的。道歉,如果這是模糊的,或者我沒有提供足夠的信息,我對此很新。

+0

那麼,什麼是在'從是在dc.Bekos'你爲什麼要'ToArray的()'呢?爲什麼不'ToList()'?有了ToList,你可以通過返回bool的'Any()'方法檢查它是否有任何內容。或者在做任何事情之前檢查它是否是「Nothing」。 – Jeremy 2013-04-11 10:01:34

+0

謝謝Jeremy的回覆,我注意到'從dc.Bekos'是錯誤的,它應該是'從beko在dc.Bekos'。 Beko是我Beko.dbml中的一個Bekos。我將'be'改爲'Beko',但我仍然沒有將價值分配給'天'。我將相應地編輯我的文章,因爲我有LINQ to SQL語句在其他頁面上使用'Beko in dc.Bekos'正確工作 – Jimsan 2013-04-11 11:05:11

+0

試着在這個Dim間設置一個斷點Dim dsList =(From b In dc.Bekos where b.dateStamp <= endDate和_b.DateStamp> = startDate _select b).ToList()'看看列表裏面有什麼'' – Jeremy 2013-04-11 11:13:05

回答

1

你在你的代碼中創建一個新的局部變量days

Dim days = (From Beko In dc.Bekos _ 

,而不是你的查詢結果分配給你的類變量days。因此,您的calBeko_DayRender方法中的天數爲Nothing,您將得到例外。

你的代碼應該是

days = (From Beko In dc.Bekos _ 
       Where Beko.DateStamp <= endDate And _ 
       Beko.DateStamp >= startDate _ 
       Order By Beko.DateStamp _ 
       Select New DateTime(Beko.DateStamp.Year, _ 
            Beko.DateStamp.Month, _ 
            Beko.DateStamp.Day) Distinct).ToArray() 
+0

棒極了,作品一種享受。這也是一個基本的錯誤。非常感謝你 – Jimsan 2013-04-11 11:41:36