如何计算从组合框中选择的项目的选票

How to tally votes from the item selected from combobox

用户从组合框中选择 his/her 候选人,当单击按钮 "vote" 时,文本框中将显示选票统计。我的代码不起作用,我不知道为什么。这是我的代码:

void BtnVoteClick(object sender, EventArgs e)
{
    // I already added the items from the properties tab
    if (comboxCandidate.SelectedItem == "VAL") 
    {
        int ctrVal = 0;
        ctrVal += 1;
        tbVal.Text = ctrVal.ToString();
    }

   if (comboxCandidate.SelectedItem == "LESTER")
   {
        int ctrLester = 0;
        ctrLester +=1;
        tbLester.Text = ctrLester.ToString();
    }
}

你没有说为什么它不能正常工作,但看看你的代码你会发现:

int ctrVal = 0;
ctrVal += 1;
...
int ctrLester = 0;
ctrLester +=1;

在这里,您在每次执行 if 语句时创建一个名为 ctrVal/ctrLester 的新变量,然后递增它。所以这个值只会是 1。每次你点击你的按钮时,变量都会被重新初始化。

如果要保持全局计数,则需要将变量的声明和初始化移动到 class 级别。

所以你有这样的东西:

public partial class Form1 : Form
{
    int ctrVal = 0;
    int ctrLester = 0;
...

void BtnVoteClick(object sender, EventArgs e)
{
     if (comboxCandidate.SelectedItem.Equals("VAL"))
     {
        ctrVal += 1;
        tbVal.Text = ctrVal.ToString();
     } 
     else if (comboxCandidate.SelectedItem.Equals("LESTER"))
     {
        ctrLester +=1;
        tbLester.Text = ctrLester.ToString();
     }
 }

PS:你也应该使用等号来比较字符串,所以我更新了它。