Board index » cppbuilder » Counting checked or unchecked checkboxes

Counting checked or unchecked checkboxes

Greetings,

What is the most efficient way to count the number of TCheckbox components
on on a form or frame which are checked (or unchecked as the case may be).

I could do it by looping through all the controls and then keeping a counter
but this just seems to be overkill.

Thanks,

Robert Lancaster

 

Re:Counting checked or unchecked checkboxes


That's probably the only reliable way you could do it:

    int iChecked = 0;
    int iUnchecked = 0;

    for(int x = 0; x < ComponentCount; x++)
    {
        TCheckBox *checkbox = dynamic_cast<TCheckBox*>(Components[x]);
        if(checkbox)
        {
            if(checkbox->Checked)
                iChecked++;
            else
                iUnchecked++;
        }
    }

Unless you assign all checkboxes to use the same OnClick event handler, then
you can do this instead:

    void __fastcall TForm1::MyClickHandler(TObject *Sender)
    {
        TCheckBox *checkbox = dynamic_cast<TCheckBox*>(Sender);
        if(checkbox)
        {
            iChecked += (checkbox->Checked) ? 1 : -1;
            iUnchecked += (checkbox->Checked) ? -1 : 1;
        }
    }

Chances are, you already have OnClick handlers assigned, though.

Gambit

"Robert Lancaster" <robert.lancas...@thales-geosolutions.com> wrote in
message news:3c874d92_2@dnews...

Quote
> I could do it by looping through all the controls and then keeping
> a counter but this just seems to be overkill.

Other Threads