未正确计算所选CheckBoxList项的计数

时间:2015-12-04 10:20:51

标签: if-statement for-loop count checkboxlist

我目前正在尝试将CheckBoxList的计数与项目的if和else语句结合使用。如果计数不等于2,我有一个标签,提示用户选择两个模块,但计数没有正确计算。任何帮助,将不胜感激。以下是有问题的代码:

protected void RegisterButton_Click(object sender,EventArgs e)     {

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["UniString"].ConnectionString);
    //This integer will hold the number of modules selected
    Int32 amount = 0;

    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {
        //amount will increment each time a module checkbox is checked
        if (CheckBoxList1.Items[i].Selected)
        {
            amount = amount++;

        }

        //If amount is not equal to 2 the code below will run
        if (amount != 2)
        {
        //If the number of modules selected is not equal to 2 then this message is displayed and the background of the label in the markup is turned red to draw attention

            ModuleSelectionMessage.Text = "Please select 2 modules to successfully register";
            ModuleSelectionMessage.BackColor = System.Drawing.Color.Red;

        }
        else
        {...

1 个答案:

答案 0 :(得分:0)

amount = amount++未正确分配金额值, 使用amount++amount= amount + 1代替..

for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {   

        //amount will increment each time a module checkbox is checked
        if (CheckBoxList1.Items[i].Selected)
        {
            amount = amount + 1;

        }

        //other code...
}