Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically click on a CheckBox

Is there a way to programmatically generate a click event on a CheckBox? I am looking for an equivalent to Button.PerformClick();

like image 698
Grzenio Avatar asked Nov 19 '09 15:11

Grzenio


4 Answers

Why do you need to simulate a click, doesn't this line of code fits your need?

myCheckBox.Checked = !myCheckBox.Checked;

If you need to execute logic when the state of the CheckBox changes, you should use CheckedChanged event instead of Click.

private void CheckBox1_CheckedChanged(Object sender, EventArgs e)
{
   MessageBox.Show("You are in the CheckBox.CheckedChanged event.");
}
like image 67
Jeff Cyr Avatar answered Oct 23 '22 21:10

Jeff Cyr


Why do you want to generate a click event on the CheckBox?

If you want to toggle it's value:

theCheckBox.Checked = !theCheckBox.Checked;

If you want to trigger some functionality that is connected to the Click event, it's a better idea to move the code out from the Click event handler into a separate method that can be called from anywhere:

private void theCheckBox_Click(object sender, EventArgs e)
{
    HandleCheckBoxClick((CheckBox)sender);
}

private void HandleCheckBoxClick(CheckBox sender)
{
    // do what is needed here
}

When you design your code like that, you can easily invoke the functionality from anywhere:

HandleCheckBoxClick(theCheckBox);

The same approach can (and perhaps should) be used for most control event handlers; move as much code as possible out from event handlers and into methods that are more reusable.

like image 45
Fredrik Mörk Avatar answered Oct 23 '22 22:10

Fredrik Mörk


Those solutions above calls Checkbox.CheckedChanged event.

If you want to explicitly call Click event you can this:

checkBox1_Click(checkBox1, null);
like image 4
cacoroto Avatar answered Oct 23 '22 22:10

cacoroto


I'm still setting up a new workstation so I can't research this properly at the moment, but with UI Automation maybe it's possible that the checkbox supports the IInvokeProvider and you can use the Invoke method?

like image 1
scwagner Avatar answered Oct 23 '22 22:10

scwagner