如何查找和替换ComboBox中的项目

时间:2015-07-16 21:01:34

标签: c++ combobox c++builder

在C ++ Builder XE8中,我使用以下方法将项目插入到ComboBox中:

MyComboBox->Items->BeginUpdate();
MyComboBox->Items->Insert(0, "Title");
MyComboBox->Items->Insert(1, "Google");
MyComboBox->Items->Insert(2, "Yahoo");
MyComboBox->Items->Insert(3, "127.0.0.1");
MyComboBox->ItemIndex = 0;
MyComboBox->Items->EndUpdate();

我想知道如何将第3项127.0.0.1替换为" xxx.0.0.1"。我尝试过使用StringReplace(),但没有运气。

1 个答案:

答案 0 :(得分:2)

首先,您的示例应该使用Add()而不是Insert()(以及try/__finally块或RAII包装器,以防抛出异常):

MyComboBox->Items->BeginUpdate();
try {
    MyComboBox->Items->Add("Title");
    MyComboBox->Items->Add("Google");
    MyComboBox->Items->Add("Yahoo");
    MyComboBox->Items->Add("127.0.0.1");
    MyComboBox->ItemIndex = 0;
}
__finally {
    MyComboBox->Items->EndUpdate();
}

现在,如果您知道要更改的项目始终是第四项,那么只需直接更新它:

MyComboBox->Items->Strings[3] = "xxx.0.0.1";

如果您需要搜索它,请使用IndexOf()

int index = MyComboBox->Items->IndexOf("127.0.0.1");
if (index != -1)
    MyComboBox->Items->Strings[index] = "xxx.0.0.1";
相关问题