Home > Back-end >  How to count checked checkbox values in C#
How to count checked checkbox values in C#

Time:09-21

I'm new to C# and trying to learn a few things. For example, I can't get the process beneath together. What am I doing wrong?

The issue I get is that when all 4 checkboxes are selected I only get 5 as result as they are all 5 selected...? and must be 20 (4x5)

        //CheckCheckedCheckboxes
        int Totalchecked = 0;
        if (CheckBox1.Checked)
        {
            Totalchecked = 5;
        }
        if (CheckBox2.Checked)
        {
            Totalchecked = 5;
        }
        if (CheckBox3.Checked)
        {
            Totalchecked = 5;
        }
        if (CheckBox4.Checked)
        {
            Totalchecked = 5;
        }

        var totalselected = Totalchecked ;
        labelHeader.Text = Convert.ToString(totalselected);

CodePudding user response:

private void button1_Click(object sender, EventArgs e)
{
    int Totalchecked = 0;
    int TotalValue = 0;
    foreach (Control item in this.Controls)
    {
        if(item is CheckBox)
        {
            if (((CheckBox)item).Checked)
                Totalchecked  ;
        }

    }

    //If you consider, each check box value as a 5, just multiply Totalchecked * 5
    TotalValue = Totalchecked * 5;
    MessageBox.Show(TotalValue.ToString());
}

But the above approach is not good when forms contain more than these checkboxes, So just add your checkboxes into the Group box and, you can get a count of the checked checkboxes as follows,

int Totalchecked = groupBox1.Controls.OfType<CheckBox>().Where(c => c.Checked).Count();

Updated: Based on your comment, you can set Tag value for a each Check box as,

checkBox1.Tag = 5;
checkBox2.Tag = 10;

int totalValueOfeachCheckboxes = 0;

foreach (Control item in this.Controls)
{
    if(item is CheckBox)
    {
        if (((CheckBox)item).Checked)
        {
            totalValueOfeachCheckboxes = totalValueOfeachCheckboxes   Convert.ToInt32(item.Tag);
        }           
    }
}
MessageBox.Show(totalValueOfeachCheckboxes.ToString());

CodePudding user response:

You can loop over them and iterate on the controls on the form.

   foreach(Control c in this.Controls)
   {
      if(c is CheckBox)
      {
         // Do stuff here/logic
      }
   }

Or do a more LINQ/Lamba-ish type approach of

    var checkList = YourForm.Controls.OfType<CheckBox>().Where(x => x.Checked).ToList();
    
    
    checkList.ForEach(x => {
        //Do stuff  here

    });
  •  Tags:  
  • c#
  • Related