2015-04-23 33 views
1

我目前正在試圖找出如何顯示從列表框中的最高分數的學生,即列表框中將顯示以下信息顯示列表框最大值(最高分)從字符串轉換成整數

「姓名:湯姆得分:18"
「名稱:丹得分:15」
「姓名:弗雷德刻痕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)) 
 
    

回答

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

非常感謝你的傢伙。 – qewpee

+1

請注意,這隻會在分數是2位時才起作用......如果分數大於或小於2位,您將需要適當編碼.... – Mych

0

您試圖像一個字符串轉換「姓名:弗雷德刻痕12」的整數,你需要先解析字符串只有你想要的整數,然後將其轉換爲整數。

喲可以這樣做,考慮到分數只能有兩位數。

Dim str As String = lstListbox.Items(i) 
Dim scoreStr As String = str.substring(str.Length - 2) 

然後你將scoreStr轉換爲Integer並使用它。

您也可以將所有分數存儲在變量(即數組)中,然後從中選取值。

相關問題