[英]Conversion of type string " " to double not valid exception in vb.net code
我正在嘗試上傳一個包含兩條記錄的 csv 文件。 下面的代碼執行了兩次,第三次我得到了這個異常----類型字符串“”的轉換無效我放了一個調試器,在那里我找到了 excel 表的兩列的值,但是第三次我得到了這個例外。 非常感謝您的幫助。 下面是代碼。
Public Function GetLocationInformation(stream As Stream) As List(Of CsvPropLocation) _
Implements ICsvHandling.GetLocationInformation
If stream Is Nothing Then Return Nothing
Dim locations = New List(Of CsvPropLocation)
Using reader = New StreamReader(stream)
Dim config = New CsvConfiguration(CultureInfo.InvariantCulture) With {
.HasHeaderRecord = True,
.IgnoreBlankLines = False
}
Using csv = New CsvReader(reader, config)
Using dataReader As New CsvDataReader(csv)
Dim dt = New DataTable()
dt.Load(dataReader)
For Each row As DataRow In dt.Rows
Dim propLocation As CsvPropLocation
'find or create a propLocation
If locations.Any(Function(x) x.nLocationNumber = row("LocNum")) Then ######Got exception here ######
propLocation = locations.First(Function(x) x.nLocationNumber = row("LocNum"))
Else
propLocation = New CsvPropLocation(row("LocNum"))
locations.Add(propLocation)
End If
'do building stuff.
Dim building = ParseRowIntoBuilding(row)
propLocation.AddBuilding(building)
Next
End Using
End Using
End Using
Return locations
End Function
將您的線路更改為
Dim number As Double
If Double.TryParse(row("LocNum"), number ) AndAlso locations.Any(Function(x) x.nLocationNumber = number )
這樣,您可以確保 number 只有在從 row("LocNum") 獲取有效值時才會被評估
另請記住,必須控制 Else 部分,因為 New CsvPropLocation(row("LocNum")) 可能期望一個不在位置內的有效 Double ,因此更改為:
Else If Double.TryParse(row("LocNum"), number ) 'You can check against number = 0
'if zero isn't a valid value for number
'(or initialize number to a known invalid value and check against it)
'if yuo didn't want a double try parse
propLocation = New CsvPropLocation(number)
locations.Add(propLocation)
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.