【问题标题】:Count of CheckBoxList items selected isn't being calculated correctly未正确计算所选 CheckBoxList 项目的计数
【发布时间】:2015-12-04 10:20:51
【问题描述】:

我目前正在尝试获取 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
        {...

【问题讨论】:

    标签: if-statement for-loop count checkboxlist


    【解决方案1】:

    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...
    }
    

    【讨论】:

    • 嗨,我之前尝试过使用这些值,但问题仍然存在
    • 您好,当我选择 2 个复选框时,它仍然显示错误消息
    • 如果选择 2 时出现错误?那么问题将是您的else 语句块区域。请检查..
    • 嗨,我的意思是即使我选择了 2(应该选择的值),错误消息仍然会出现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多