为什么它只显示一个结果

时间:2016-09-15 08:04:06

标签: vb.net listbox voting-system

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

我的问题是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

1 个答案:

答案 0 :(得分:0)

试试这个:

假设候选人和他/她的投票的索引相同:

  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的内容。

相关问题