如何查找和替换组合框中的项

How to find and replace an items in a ComboBox

本文关键字:组合 替换 何查找 查找      更新时间:2023-10-16

在c++ Builder XE8中,我使用以下方法将项插入到组合框中:

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(),但没有运气。

首先,您的示例应该使用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";