Home > Enterprise >  C# Listen for checkbox chenge in groupbox
C# Listen for checkbox chenge in groupbox

Time:12-13

I have a groupbox with 16 checkboxes and I need to run an event that knows the button pressed if any of them change states.

I know I can add an on click action for each but is there a cleaner way of doing this? Showing layout of the 16 buttons

CodePudding user response:

I realized that you can just reuse actions and cast the sender object:

private void InputSwitched(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
        }

CodePudding user response:

You can handle checked events of all the checkboxes of the groupbox, using a single event handler, like this:

public Form1()
{
    InitializeComponent();
    groupBox1.Controls.OfType<CheckBox>()
        .ToList().ForEach(c => c.CheckedChanged  = C_CheckedChanged);
}
private void C_CheckedChanged(object sender, EventArgs e)
{
    var c = (CheckBox)sender;
    MessageBox.Show($"{c.Name} - Checked: {c.Checked}");
}

CodePudding user response:

Here's what I meant in the comments about dynamically creating the controls.

You can do something like this:

    private List<CheckBox> _checkBoxes = null;

    public Form1()
    {
        InitializeComponent();

        var checkbox_count = 15;

        _checkBoxes =
                Enumerable
                    .Range(0, checkbox_count)
                    .Select(x => new CheckBox()
                    {
                        Text = $"CheckBox {x}",
                    })
                    .ToList();

        foreach (var checkbox in _checkBoxes)
        {
            flowLayoutPanel1.Controls.Add(checkbox);
            checkbox.CheckedChanged  = (s, e)
                    => checkbox.BackColor =
                        checkbox.Checked
                            ? Color.Red
                            : Color.Blue;
        }
    }
  • Related