Home > Net >  How to write an event for multiple checkbox.Checked?
How to write an event for multiple checkbox.Checked?

Time:04-02

I am building a plumbing services windows form that has three checkboxes, each with different totals representing the type of service. If two or more were checked how would I combine their totals so they can be displayed in a designated text box rather than just displaying the individual amount.

        private void apprenticeCheck_CheckedChanged(object sender, EventArgs e)
        {
            double apprenticeCost;
            apprenticeCost = 55.00   CALLOUT_AMOUNT;

            if (apprenticeCheck.Checked)
                serviceTotalText.Text = apprenticeCost.ToString("C");

CodePudding user response:

You can create a variable for keeping track of total amount and update this variable at every check of any checkbox

    const int CALLOUT_AMOUNT = 5;
    double TotalCost = 0;

    private void apprenticeCheck_CheckedChanged(object sender, EventArgs e)
    {
        double apprenticeCost = 55.00   CALLOUT_AMOUNT;

        if (apprenticeCheck.Checked)
            TotalCost  = apprenticeCost;
        else
            TotalCost -= apprenticeCost;

        serviceTotalText.Text = TotalCost.ToString("C");
    }

CodePudding user response:

A simple approach, create a class to represent a service.

public class Service
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Cost { get; set; }
}

Using a private list of CheckBox, assign OnCheckedChanged event for each CheckBox. In the Check changed event use a lambda statement to get total against those CheckBoxes that are checked.

Code assumes the CheckBox controls are directly on the form.

namespace PlumbingExample
{
    public partial class Form1 : Form
    {
        private readonly List<CheckBox> _checkBoxes;
        private double _serviceCharge = 5d;

        public Form1()
        {
            InitializeComponent();
            Shown  = OnShown;
            _checkBoxes = Controls.OfType<CheckBox>().ToList();
        }

        private void OnShown(object sender, EventArgs e)
        {
            Service1CheckBox.Tag = new Service() { Id = 1, Name = "Service 1", Cost = 45.00d };
            Service2CheckBox.Tag = new Service() { Id = 2, Name = "Service 2", Cost = 55.00d };
            Service3CheckBox.Tag = new Service() { Id = 3, Name = "Service 3", Cost = 65.00d };

            _checkBoxes.ForEach(x => x.CheckStateChanged  = CheckBoxOnCheckedChanged);

            serviceTotalText.Text = "$0.00";
        }

        private void CheckBoxOnCheckedChanged(object sender, EventArgs e)
        {
            var total = _checkBoxes
                .Where(checkBox => checkBox.Checked)
                .Select(checkBox => ((Service)checkBox.Tag).Cost   _serviceCharge)
                .Sum();

            serviceTotalText.Text = total.ToString("C");
            serviceTotalText.Tag = total;
        }
    }
}
  • Related