2013-06-18 56 views
0

喜誰能幫我這個即時消息與此錯誤現在坐了有一個小時,但無法弄清楚如何解決這個錯誤我的代碼是轉換無效

'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) 
+0

使用'新的datetime(ARR(I))' – user1937198

+0

感謝快速reply..let我嘗試的..哎 – daniloJR

+0

對不起,作爲一個菜鳥但我有另一個問題..在嘗試代碼後,它返回此錯誤「從字符串」00:00:00「轉換爲類型」長「無效。」 – daniloJR

回答

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 
} 

UPDATE

關於你提到的第二個問題,有很多這樣做的方法,但最簡單的是將值直接轉換爲TimeSpan,並且不與理會DateTime變量。

+0

是的,它的所有我的錯傢伙..感謝幫助我修復錯誤它的確定和現在運行.. – daniloJR

+0

即時通訊對所有的麻煩..我只是忘記改變後刪除lblsattotal .text和lblsuntotal.text xD – daniloJR

+0

1000 upvotes to you。此外,OP應該使用'For Each'循環。爲循環索引變得幾乎完全沒有必要。 –

0

您已經爲七個項目創建了一個數組,但是您只將值放在前五個中。當循環遍歷數組中的所有項目時,最後兩個項目都爲空,因此它們不能轉換爲日期。

五個項目創建一個數組:

Dim arr(4) As String 
+0

哇呀..我忘了改變那一..因爲之前我試圖計算星期六和星期日這就是爲什麼我使用6 – daniloJR