return a value from checkbox_CheckChanged

13,507

Solution 1

The Controls event handlers are always "void" and you cant change the return type. Instead you can take an external variable and you change that value only in when the CheckedChanged Event occurs.

public bool checkedthecheckbox { get; set; }

CheckBox testchbox = new CheckBox();

private void Form1_Load(object sender, EventArgs e)
{
    testchbox.CheckedChanged += new EventHandler(testchbox_CheckedChanged);
}

void testchbox_CheckedChanged(object sender, EventArgs e)
{
    if (testchbox.Checked)
        checkedthecheckbox = true;
    else
        checkedthecheckbox = false;
}

Solution 2

You can get the value from 'sender' object.

CheckBox chk = (CheckBox) sender;
bool result = chk.Checked;

Solution 3

You can get the state of the Checkbox by casting the sender object from the event arguments:

public void Method1()
{
    CheckBox checkBox = new CheckBox();
    checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);
}

void checkBox_CheckedChanged(object sender, EventArgs e)
{
    CheckBox c = (CheckBox)sender;
    bool resutlt = c.Checked;
}

Hope this helps!

Solution 4

You can use CheckState.Checked or CheckState.Unchecked, which is built in C#. Example:

for (int i = 0; i < lsbx_layers.Items.Count; i++) {
    if (lsbx_layers.GetItemCheckState(i) == CheckState.Checked) {
        //set  boolean variable to true
    } else if (lsbx_layers.GetItemCheckState(i) == CheckState.Unchecked) {
         //set  boolean variable to false
    }
}
Share:
13,507

Related videos on Youtube

user995689
Author by

user995689

Updated on June 04, 2022

Comments

  • user995689
    user995689 almost 2 years

    How can I get a value returned from the checkbox_CheckChanged event please? Its a winforms app, and both the form and the checkbox are created programmatically. Thanks for all and any help.

    • Sai Kalyan Kumar Akshinthala
      Sai Kalyan Kumar Akshinthala over 12 years
      Where's your code. Can you provide that.
  • user995689
    user995689 over 12 years
    Thanks to all who answered, and specially to skk for the particular answer.