从字符串""转换输入'日期'无效

时间:2013-06-18 20:36:29

标签: vb.net

嗨,任何人都可以帮我解决这个问题,因为这个错误就像现在一个小时一样,但是无法弄清楚如何修复这个错误我的代码是

'Calculate the total of hours worked

'Declare a Date Time Variable   

    Dim TempDateTime As DateTime = Nothing
    'Declare a local time span variable
    Dim TempTimeSpan As New TimeSpan
    'Declare a array of type string and set the size equal to number of text boxes.
    Dim arr(6) As String
    'set the value for text boxs to array
    arr(0) = lblmontotal.Text
    arr(1) = lbltuestotal.Text
    arr(2) = lblwedtotal.Text
    arr(3) = lblthurstotal.Text
    arr(4) = lblfridtotal.Text

    For i As Integer = 0 To arr.Length - 1
        TempDateTime = CDate(arr(i))
        TempTimeSpan = TempTimeSpan.Add(New TimeSpan(TempDateTime.Hour, TempDateTime.Minute, 0))
    Next
    'showing the total time.
    lbltotalhours.Text = (TempTimeSpan.Hours & ":" & TempTimeSpan.Minutes)

2 个答案:

答案 0 :(得分:4)

您尚未为数组元素5和6指定任何内容。当您在循环中点击这些元素时,CDate将返回您所描述的错误。

提示 - 改为像这样实例化你的数组。这样,编译器会为你计算长度并避免这样的错误。

'set the value for text boxs to array
Dim arr As String() = {
    lblmontotal.Text,
    lbltuestotal.Text,
    lblwedtotal.Text,
    lblthurstotal.Text,
    lblfridtotal.Text
}

<强>更新

关于你的第二个问题,有很多方法可以做到这一点,但最简单的方法是将值直接转换为TimeSpan,而不必担心DateTime变量所有

答案 1 :(得分:0)

您已为七个项目创建了一个数组,但之后只将值放在前五个中。循环遍历数组中的所有项时,最后两个为空,因此无法将它们转换为日期。

为五个项目创建一个数组:

Dim arr(4) As String
相关问题