如何从SQL表中提取特定日期范围内的记录?

时间:2018-02-19 17:24:09

标签: sql .net vb.net

我正在使用我的vb.net Windows窗体应用程序中的用户模块。 所以我有一个SQL表,它有三列,数据类型为" Date"。我想提取属于指定日期范围的记录并将其显示在列表视图中。 我的表格如下:

enter image description here

对于申请按钮,我写了以下功能:

'FUNCTION: APPLY_DATE_FILTER(): FILTER THE LIST ACCORDING TO SELECTED DATE COLUMN 
Private Sub apply_date_filter(ByVal radio_create As RadioButton, ByVal radio_lastlogin As RadioButton, ByVal radio_lastedit As RadioButton, ByVal date1 As DateTimePicker, ByVal date2 As DateTimePicker, ByVal list As ListView)
    Dim sel As String
    If list.Items.Count = 0 Then
        If radio_create.Checked = True Then
            sel = "SELECT * FROM user_master WHERE created BETWEEN '" & date1.Text & "' AND '" & date2.Text & "'"
        ElseIf radio_lastedit.Checked = True Then
            sel = "SELECT * FROM user_master WHERE lastchange BETWEEN '" & date1.Text & "' AND '" & date2.Text & "'"
        ElseIf radio_lastlogin.Checked = True Then
            sel = "SELECT * FROM user_master WHERE lastlogin BETWEEN '" & date1.Text & "' AND '" & date2.Text & "'"
        End If
        Dim cnn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\RSMS_DB.mdf;Integrated Security=True;User Instance=True")
        Dim da As New SqlDataAdapter(sel, cnn)
        Dim ds As New DataSet
        da.Fill(ds)
        If ds.Tables(0).Rows.Count = 0 Then
            MsgBox("There are no users found within the date-range you specified! Please try again with a valid entry!", MsgBoxStyle.OkOnly, "USER NOT FOUND")
        Else
            For m As Integer = 0 To ds.Tables(0).Rows.Count - 1
                Dim lvi As New ListViewItem
                lvi.Text = ds.Tables(0).Rows(m)(0).ToString
                lvi.SubItems.Add(ds.Tables(0).Rows(m)(1).ToString)
                lvi.SubItems.Add(ds.Tables(0).Rows(m)(2).ToString)
                lvi.SubItems.Add(ds.Tables(0).Rows(m)(5).ToString)
                lvi.SubItems.Add(ds.Tables(0).Rows(m)(7).ToString)
                lvi.SubItems.Add(ds.Tables(0).Rows(m)(8).ToString)
                lvi.SubItems.Add(ds.Tables(0).Rows(m)(9).ToString)
                If ds.Tables(0).Rows(m)(10).ToString = "1" Then
                    lvi.SubItems.Add("Administrator")
                ElseIf ds.Tables(0).Rows(m)(10).ToString = "0" Then
                    lvi.SubItems.Add("Ordiary")
                End If
                list.Items.Add(lvi)
            Next
        End If
    End If
End Sub

当我点击“应用”时,我在da.Fill(ds)处收到错误,"从字符串转换日期和/或时间时转换失败。" 提前致谢。 :)

0 个答案:

没有答案