0

我正在为大学做一个项目,并创建了一个带有简单午餐菜单的面板。菜单的每个项目(如果由复选框呈现)。我想要发生的是每次选中或取消选中新项目时都会更改总数。这是我迄今为止尝试使用的代码,但是当我运行它时它似乎冻结了程序。我尝试使用 while 循环来不断检查复选框是选中还是未选中。

有一个面板,里面有复选框,面板底部有一个标签。

在使用 while 循环检查每个复选框的选中状态并相应地更新标签文本方面,我是否处于正确的行列?

private void plBistro_Paint(object sender, PaintEventArgs e)
        {
            //create a variable to hold the total
            double bistotal = 0.0;

            while(bistotal != 99){
                //check if they chose a ham sandwich
                if(cbHamSandwich.Checked == true){

                    //if they did add 1.20 to the value of bistotal
                    bistotal = bistotal + 1.20;
                }

            string bistotalString = Convert.ToString(bistotal);

            lblBistroTotal.Text = bistotalString;
        }
        }
4

7 回答 7

4

您对此采取了错误的方法。复选框应引发事件,事件处理程序应负责维护总数。

于 2012-05-10T16:56:50.257 回答
3

是的,这将导致无限循环,更改标签将导致重绘...

为 CheckBox.CheckChanged 事件添加一个处理程序并在其中执行您想要的操作。

于 2012-05-10T16:57:18.743 回答
2

您的代码中有一个无限循环,而且 Paint 事件不是进行此计算的地方。你想要更多类似的东西:

private void cbHamSandwich_CheckChanged (object sender, EventArgs e)
{
    CalcTotal();
}

private void CalcTotal()
{
    double bistotal = 0.0;

    if(cbHamSandwich.Checked == true)
    {
        //if they did add 1.20 to the value of bistotal
        bistotal = bistotal + 1.20;
    } 

    // more selected values to add to total

    lblBistroTotal.Text = bistotal.ToString("c");
}

CheckChanged为需要更改总价的每个选项添加事件。

于 2012-05-10T17:03:57.900 回答
0

我猜这里发生的事情是在 UI 线程上访问或设置某些内容(访问 cbHamSandwich 或在 lblBistroTotal 上设置文本)每次设置时都会触发一个新的绘制事件,因此是一个无限循环。您可能应该在计时器中执行此更新,或侦听其他 UI 事件。

编辑: 现在我看起来更近了,似乎 while 循环本身也是一个基本问题。您基本上是说,当检查复选框时,您想将总数一直升至至少99(而总数不是99,如果检查了复选框,请继续添加)。但是一旦达到99,它就会跳出那个循环。这不是你最关键的问题。

于 2012-05-10T17:00:27.307 回答
0

你想给你的复选框 onchanged handlers..类似:

private void chkBox_CheckedChanged(object sender, System.EventArgs e) {
  if (sender is CheckBox) { 
    CheckBox checkbox = sender as CheckBox;

    //do you checkbox accounting here
    if (checkbox.Checked){
      //blah
    }else{
      //blah
    }
  }
}

// elsewhere..assign event handler
chkBox.CheckedChanged += new EventHandler(chkBox_CheckedChanged);
于 2012-05-10T17:02:10.773 回答
0

CheckedChanged 和 CheckStateChanged 事件将被触发。像这样使用它:

private void cbHamSandwich_CheckedChanged(object sender, EventArgs e)
{
    //Verify(Check) the Checked property of the Checkbox and
    //Your Code Goes Here
}

并且 :

private void cbHamSandwich_CheckStateChanged(object sender, EventArgs e)
{
    //Verify(Check) the CheckState property of the Checkbox and
    //Your Code Goes Here
}
于 2012-05-10T17:03:12.330 回答
0

如前所述,在绘制事件中处理它并不是您真正想要做的。我的建议是将您的代码放在所有复选框都连接到的事件处理程序中。显然,比“checkBox2_CheckStateChanged”更合适的名称会更好,但您可以随意命名函数,真的。

设置两个控件使用相同的事件处理程序

编辑:或者您可以为每个复选框创建一个 CheckChanged 事件处理程序并调用一个函数来计算您的总数。

于 2012-05-10T17:04:34.087 回答