我目前正试图弄清楚如何从列表框中显示最高学生分数,即列表框显示以下消息
“姓名:汤姆得分:18” “姓名:丹分数:15” “姓名:Fred得分12”
我希望它只显示最高分。
每当我尝试运行它时,它都无法将lstlistbox.items(0)
从string
转换为integer
。
很抱歉,如果我的解释不是很清楚。
Private Sub AddlistBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddlistBtn.Click
Dim Name As String = StdName.Text
Dim strformat As String
strformat = String.Format("Name: " & Name & " Score: " & VTotal)
lstListbox.Items.Add(strformat)
End Sub
Private Sub LblStatusBox_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LblStatusBox.Click
End Sub
Private Sub BtnHighestScr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnHighestScr.Click
Dim i As Integer = 0
Dim lstsize As Integer = lstListbox.Items.Count
Dim high As Integer = CInt(lstListbox.Items(0))
Do While (i < lstsize - 1)
If (CInt(lstListbox.Items(i)) > high) Then
high = CInt(lstListbox.Items(i))
End If
i += 1
Loop
MessageBox.Show(CStr(high))
答案 0 :(得分:1)
你可以这样使用
Dim max As Integer = 0
Dim result = ""
For Each s As String In lstListbox.Items
Dim x = CInt(s.Substring((s.LastIndexOf(":") + 2)))
If max < x Then
max = x
result = s
End If
Next
MsgBox(result)
答案 1 :(得分:0)
您正在尝试将“Name:Fred Score 12”之类的字符串转换为Integer,您需要首先解析字符串以仅包含所需的整数,然后将其转换为整数。
考虑到分数只能有两位数,哟可以这样做。Dim str As String = lstListbox.Items(i)
Dim scoreStr As String = str.substring(str.Length - 2)
然后你将scoreStr转换为Integer并使用它。
您还可以将所有分数存储在变量(即数组)中,然后从中获取值。