为什么只显示一个结果

Why is it only displaying one result

此程序应该接受有效候选人进行投票,将在文本框中键入的姓名添加到列表框中。在列表框中,用户可以双击他们选择的候选人。单击计票按钮后,显示候选人姓名和选票的列表框将出现在另一个列表框旁边。

我的问题是 lstTallies 只显示最后投票的候选人。 下面是我的代码

Public Class Form1
    Dim maxVotes As Integer
    Dim winner As String
    Dim votes() As Integer
    Dim index As Integer
    Dim candidates As String

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        If Not isValidInput(txtNewCandidate.Text) Then
            Exit Sub
        End If
        lstCandidates.Items.Add(txtNewCandidate.Text)
        txtNewCandidate.Clear()
        txtNewCandidate.Focus()
        ReDim Preserve votes(index)
        index += 1
    End Sub

    Private Function isValidInput(ByRef firstName As String) As Boolean
        If IsNumeric(txtNewCandidate.Text) Or txtNewCandidate.Text = "" Then
            MsgBox("Please input a valid candidate name.")
            txtNewCandidate.Focus()
            Return False
        Else
            Return True
        End If
    End Function

    Private Sub btnTally_Click(sender As Object, e As EventArgs) Handles btnTally.Click
        lstTallies.Visible = True
        lblTally.Visible = True
        lstTallies.Items.Add(lstCandidates.Text & " " & votes(lstCandidates.SelectedIndex))
    End Sub

    Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
        If lstCandidates.SelectedIndex = -1 Then
            MsgBox("Select a candidate by double-clicking")
        End If
        votes(lstCandidates.SelectedIndex) += 1
        MsgBox("Vote Tallied")
    End Sub
End Class

试试这个:

假设候选人和his/her投票的索引相同:

  Private Sub btnTally_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTally.Click
    lstTallies.Visible = True
    lblTally.Visible = True
    For i = 0 To lstCandidates.Items.Count - 1
        lstTallies.Items.Add(lstCandidates.Items(i).ToString & " - " & votes(i))
    Next
  End Sub

您无法获取 ListBox 的内容,除非您 iterate 它。