mercredi 21 juin 2017

Determine whether the active check box is checked in Winforms

I am developing a Windows Forms Application using Visual Studio in Visual C++. My form has 96 check boxes on it. Rather than create 96 Click events, I believe that there's a way to create a single Click event that is called when any check box is clicked. Within the Click event, I need to determine whether the active checkbox is Checked or Not Checked. While this should be easy, I can't seem to figure it out!

I got it to work with the code below, but I'm sure there's a better way.

    if (sender == checkBox_D1)
    {
        if (checkBox_D1->Checked)
            isChecked = true;
    }
    else if (sender == checkBox_D2)
    {
        if (checkBox_D2->Checked)
            isChecked = true;
    }
    else
        return; // Invalid sender - should not get here!

    if (isChecked)
    {
        // Do something
    }
    else
    {
        // Do something else
    }

I also tried the code below but activeCheckBox is not a Checkbox object so it doesn't work.

Control^ activeCheckBox = ActiveControl;

activeCheckBox->Text returns the Text property of the Checkbox

activeCheckBox->Checked doesn't compile. The error is 'Checked' : is not a member of 'System::Windows::Forms::Control'

It seems like sender has the data that I need but I don't know how to access it.

Is there a way to declare a Checkbox as follows?

CheckBox activeBox;

and then assign activeBox to the Checkbox that has the focus activeBox = ???

// Then just need to do this!
if (activeBox.Checked)
    isChecked = true;

Thank you for the help.




Aucun commentaire:

Enregistrer un commentaire