m170115
m170115

Reputation: 121

Checking for string in a combobox list

I need to program my combobox in such a way that when checkbox1 is clicked, "1" will be added into the combobox list, and if checkbox1 is unchecked, "1" will be removed from the list. Similarly for other checkboxes (eg. checkbox2, checkbox3, etc).

I can add "1" to the list, but am not sure what code should be used for checking and removing. This is how I have coded it:

void MyProject::OnBnClickedCheckBox1()
{
    if( //ComboBox list does not have "1")
    {
        CComboBox *pComboboxCam1 = (CComboBox *)(GetDlgItem(IDC_Cam1Combo));
        pComboboxCam1 = (CComboBox *)(GetDlgItem(IDC_Cam1Combo));
        pComboboxCam1->AddString(_T("1"));  
    }
    else
        //Remove "1" from list
}

Upvotes: 1

Views: 551

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598011

Use the CComboBox::FindString() or CComboBox::FindStringExact() method to find the index of the string, then use the CComboBox::DeleteString() method to remove it.

For example:

void MyProject::OnBnClickedCheckBox1()
{
    CButton *pCheckboxCam1 = (CButton*) GetDlgItem(IDC_Cam1Check);

    CComboBox *pComboboxCam1 = (CComboBox *) GetDlgItem(IDC_Cam1Combo);
    int index = pComboboxCam1->FindString(-1, _T("1"));

    if (pCheckboxCam1->GetCheck() == BST_CHECKED)
    {
        if (index < 0)
            pComboboxCam1->AddString(_T("1"));
    }
    else
    {
        if (index >= 0)
            pComboboxCam1->DeleteString(index);
    }
}

Upvotes: 1

Matriac
Matriac

Reputation: 382

You should either use the FindString function or the FindStringExact function. They search for the string in the combobox and return either the index, if the value is greater than or equal to 0, or CB_ERR is the search was unsuccessful.

CComboBox *pComboboxCam1 = (CComboBox *)(GetDlgItem(IDC_Cam1Combo));
 if( pComboboxCam1->FindStringExact(0,_T("1")) == CB_ERR) // first parameter is the indextStart, second one is the string
    {
    //String not found
    pComboboxCam1 = (CComboBox *)(GetDlgItem(IDC_Cam1Combo));
    pComboboxCam1->AddString(_T("1"));  
    }
    else
    //String found

Upvotes: 0

Related Questions