如何将列表框中的项目读取为整数

时间:2015-10-19 14:13:16

标签: .net vb.net string parsing listbox

我有一个列表框,但项目是字符串,当我使用此代码时。它不能确定什么是最高的,因为它是一个字符串;但代码正在运作。

我的列表框中有1 1 1,但错误说

  

附加信息:从字符串“”到“整数”类型的转换无效。

这是我的代码

    Dim max As Integer = 0
    Dim result = ""

    For Each s As Integer In GARAGE.ListBox5.Items
        If max < s Then
            max = s
            result = s
        End If
        GARAGE.Label19.Text = result
    Next

2 个答案:

答案 0 :(得分:0)

您需要将ListItem Value或Text转换为Integer,如以下示例所示

Dim max as Integer = 0
For Each i As ListItem In GARAGE.ListBox5.Items
    Dim s As Integer = 0

    'If you are sure there are all numerics use following statement
    s = Int32.Parse(i.Text)

    'in case there are non numeric values, even blanks, use following statement
    'Int32.TryParse(i.Text, s)
    If max < s Then
        max = s
    End If
Next
GARAGE.Label19.Text = max.ToString()

答案 1 :(得分:0)

您的问题似乎是ListBox中的一个值是空字符串,无法将其解析为数值。

您应该做更多这样的事情,以便抛出异常或忽略非数字值:

    Dim maxValue As Integer = 0
    For Each listBoxItem As Object In ListBox1.Items
        Dim i As Integer
        If Integer.TryParse(listBoxItem.ToString, i) Then
            If i > maxValue Then maxValue = i
        Else
            'ignore any values that are not-numeric
            'possibly throw an exception if this happens?
        End If
    Next
    MessageBox.Show("The highest value is " & maxValue.ToString)