Search code examples
c#visual-studiocheckboxlabeloperation

How to make label text(number) change by clicking checkbox?


enter image description here

Teacher gave us an assignment. Checkboxes are lessons that students may choose and labels under them are the free spots left. Basically everytime a lesson(checkbox) selected the number connected to it at label should lessen minus 1. if person unchecks it, number should return to basic.

Sorry for my English, i hope it's understandable.


Solution

  • You can try to subscribe to the CheckedChanged event for each checkbox. And use Convert.ToInt32 Method to get the value in labels. Then judge the checkbox selected via swicth statement.

    public Form1()
    {
        InitializeComponent();
    
        checkBox1.CheckedChanged += checkBox_CheckedChanged;
        checkBox2.CheckedChanged += checkBox_CheckedChanged;
        checkBox3.CheckedChanged += checkBox_CheckedChanged;
    }
    
    private void checkBox_CheckedChanged(object sender, EventArgs e)
    {
        if (((CheckBox)sender).Checked)
        {
            switch (((CheckBox)sender).Name)
            {
                case "checkBox1":
                    labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) + 1).ToString();
                    break;
                case "checkBox2":
                    labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) + 1).ToString();
                    break;
                case "checkBox3":
                    labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) + 1).ToString();
                    break;
            }
        }
        else
        {
            switch (((CheckBox)sender).Name)
            {
                case "checkBox1":
                    labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) - 1).ToString();
                    break;
                case "checkBox2":
                    labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) - 1).ToString();
                    break;
                case "checkBox3":
                    labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) - 1).ToString();
                    break;
            }
        }
    }