检查组合框列表中的字符串

Checking for string in a combobox list

我需要对我的组合框进行编程,当单击 checkbox1 时,“1”将添加到组合框列表中,如果未选中 checkbox1,则“1”将从列表中删除。对于其他复选框(例如 checkbox2、checkbox3 等)也是如此。

我可以在列表中添加“1”,但我不确定应该使用什么代码来检查和删除。这就是我的编码方式:

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
}

使用CComboBox::FindString() or CComboBox::FindStringExact() method to find the index of the string, then use the CComboBox::DeleteString()方法删除它。

例如:

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);
    }
}

您应该使用 FindString 函数或 FindStringExact 函数。他们在组合框中搜索字符串,如果值大于或等于 0,则 return 索引,或者 CB_ERR 表示搜索不成功。

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