Programmatically click on CheckBox

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

+4
source share
6 answers

Why do you pretend to click, does this line of code not suit your needs?

myCheckBox.Checked = !myCheckBox.Checked; 

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

 private void CheckBox1_CheckedChanged(Object sender, EventArgs e) { MessageBox.Show("You are in the CheckBox.CheckedChanged event."); } 
+9
source

These solutions are above calls to Checkbox.CheckedChanged.

If you want to explicitly trigger the Click event, you can do this:

 checkBox1_Click(checkBox1, null); 
+3
source

Why do you want to create a click event on a CheckBox?

If you want to switch its value:

 theCheckBox.Checked = !theCheckBox.Checked; 

If you want to call some functions associated with the Click event, it is better to translate the code 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 create your code this way, you can easily call 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 from event handlers and to methods that are more reused.

+2
source

I'm still setting up a new workstation, so I canโ€™t research it right now, but UI Automation , is it possible that the checkbox supports IInvokeProvider and you can use the Invoke method?

+1
source

I do not think that you can create a click event this way without calling the checkBox_Click event handler directly. But you can do it:

 checkBox.Checked = !checkBox.Checked; 

The CheckedChanged handler will still be called, even if you do.

0
source

You do not indicate which CheckBox control. ASP.net or Windows?

Assuming the control is using a web panel, this is a way to disable it by calling JavaScript from code ...

JavaScript function call from code

Step 1 Add Your Javascript Code

 <script type="text/javascript" language="javascript"> function Func() { alert("hello!") } </script> 

Step 2 Add 1 Script Manager to your web form and add another button

Step 3 Add this code to the button click event

 ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true); 
0
source

All Articles