abc123
abc123

Reputation: 95

Incrementing Label Value when a button is clicked

I have tried converting using CInt, TryParse, Convert.Int32, etc but nothing worked. I just need to display the total votes of the candidated when a button btnVote is clicked and display the result when I click btnResult. I've tried searching on the net also but still no luck so I came up to this website and hopefully I could solve my problem with my program in VB.net

Below is my code:

Public Class Presidential_Election

    Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
        If cboCandidates.Text = "NOLI" Then
            lblNoli.Text = Integer.Parse(lblNoli.Text) + 1
        ElseIf cboCandidates.Text = "VAL" Then
            lblVal.Text = (CInt(lblVal.Text) + 1).ToString
        ElseIf cboCandidates.Text = "LESTER" Then
            lblLester.Text = CInt(lblLester.Text) + 1
        ElseIf cboCandidates.Text = "GWAPO" Then
            lblGwapo.Text = CInt(lblGwapo.Text) + 1
        End If
    End Sub

    Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
        lblNoli.Visible = True
        lblVal.Visible = True
        lblLester.Visible = True
        lblGwapo.Visible = True
    End Sub
End Class

Upvotes: 0

Views: 4236

Answers (2)

Jonathan
Jonathan

Reputation: 83

I would set an integer counter for each candidate. Set these to 0 and then increment them as they receive a vote. When you display the results just bind the text of the label to its respective counter and make it visible. This way, you don't have to keep referencing label.text.

Upvotes: 1

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

If you haven't set the label text to be 0 at the beginning, using CInt would definitely throw an error. You have two options :

  • set all labels text to 0 and keep using CInt, or
  • use Val()

Example :

lblGwapo.Text = Val(lblGwapo.Text) + 1

Upvotes: 0

Related Questions