Asp.net IDataReader-获取要在计算中使用的SQL时间(7)字段的值

Asp.net IDataReader-获取要在计算中使用的SQL时间(7)字段的值,asp.net,vb.net,time,datareader,Asp.net,Vb.net,Time,Datareader,使用IDataReader,我需要获得时间值,以便获得时间跨度。在我的SQL数据库中,这些值是时间(7)。我收到一个错误-用户代码未处理InvalidCast异常。这是我的代码(我知道我必须重写Select语句): Dim begtime As String=reader.GetDateTime(2)您正在尝试获取日期时间类型并将其存储在字符串中。如果db将其作为日期,则将其转换为一个日期类型,如之后的行中所示。您很快!我编辑了我的帖子,说我尝试了DateTime和String。都不起作用。错误

使用IDataReader,我需要获得时间值,以便获得时间跨度。在我的SQL数据库中,这些值是时间(7)。我收到一个错误-用户代码未处理InvalidCast异常。这是我的代码(我知道我必须重写Select语句):


Dim begtime As String=reader.GetDateTime(2)
您正在尝试获取日期时间类型并将其存储在字符串中。如果db将其作为日期,则将其转换为一个日期类型,如之后的行中所示。您很快!我编辑了我的帖子,说我尝试了DateTime和String。都不起作用。错误消息还有更多内容,但您没有共享。begintimeoff和endtimeoff的列类型是什么?此代码极易受到sql注入攻击。在我的SQL数据库中,Begintimeoff和endtimeoff是时间(7)。乔尔-谢谢你指出这一点。我知道我必须重写它。现在,这是一个只有我的部门才能访问的内部网络程序。由于它可能会在其他部门使用,我将阅读有关修复此问题的内容。谢谢你的帮助!
commandvct.CommandText = "Select begindateoff, enddateoff, begintimeoff, endtimeoff, allday_yesno from tblworkhours where Employee = " & rve & " and workcode = 2"
commandvct.CommandType = CommandType.Text
commandvct.Connection = sqlConnection

sqlConnection.Open()

Using reader As IDataReader = commandvct.ExecuteReader

    While reader.Read()

        Dim begdate As Date = reader.GetDateTime(0)
        Dim enddate As Date = reader.GetDateTime(1)

        If begdate = enddate Then

            Dim allday As Boolean = reader.GetBoolean(4)

            'If all day, add 8 hours
            If (allday = True) Then

                workinghoursv = workinghoursv + 8 'Change me to your needs.
                TextBoxva2.Text = workinghoursv

                'If not all day, add difference between times
            Else
            'tried defining it as datetime and as string - neither work
                Dim begtime As String = reader.GetDateTime(2)
                Dim endtime As DateTime = reader.GetDateTime(3)

                Dim diffv As TimeSpan = (endtime).Subtract(begtime)
                Dim diff2v As Decimal = (Convert.ToDecimal(diffv.TotalMinutes)) / 60
                workinghoursv = workinghoursv + diff2v
                TextBoxva2.Text = workinghoursv


            End If