执行我的方法(下面的代码)时出现上述异常:
Sub loadDates(ByVal newDate As Date)
Dim dayCount As Integer = 0
conn = New SqlConnection(connectionString)
ds = New DataSet("Holiday")
sql = New SqlCommand("SELECT * FROM Holiday", conn)
Dim da As SqlDataAdapter = New SqlDataAdapter("SELECT date FROM Holiday", conn)
conn.Open()
da.FillSchema(ds, SchemaType.Source, "Holiday")
da.Fill(ds, "Holiday")
Dim tblHoliday As DataTable
tblHoliday = ds.Tables("Holiday")
For Each row As DataRow In tblHoliday.Rows
If Not row Is Nothing Then
For items As Integer = 0 To tblHoliday.Rows.Count Step 1
Dim dateValue As Date = row.Item(0)
If newDate = dateValue Then
dayCount += 1
End If
Exit For
Next
End If
Next
conn.Close()
If newDate.DayOfWeek = DayOfWeek.Saturday Or newDate.DayOfWeek = DayOfWeek.Sunday Then
dayCount = 2
End If
For days As Integer = dayCount To 0 Step -1
Dim dropDates As Date = New Date(newDate.Year, newDate.Month, newDate.Day - days)
ddDate.Items.Add(dropDates.ToShortDateString())
Next
End Sub
我已经将问题缩小到了方法中的For Each循环内,当我输入一个日期并且它跳过循环时它没有问题。当它必须通过循环时它崩溃了:
Dim dropDates As Date = New Date(newDate.Year, newDate.Month, newDate.Day - days)
有什么想法吗?
答案 0 :(得分:2)
减去日期而不是日期组件的天数,这样日期组件不会超出范围:
Dim dropDates As Date = New Date(newDate.Year, newDate.Month, newDate.Day).AddDays(-days)
如果newDate
没有使用Date
构造函数删除任何时间组件组件,则可以直接使用newDate
:
Dim dropDates As Date = newDate.AddDays(-days)