tags:

views:

1473

answers:

3

I want to add values to combobox in C++ builder 6. I know I can add string to combobox by string list editor.

For example, I have added this list to combobox:

car
ball
apple
bird

I want behind each text, it has their own value, so I can get the value rahter than the text when user selected a text. Just like HTML select.

But when I try to add value to each text:

ComboBox1->Items->Values[0] = "mycar";
ComboBox1->Items->Values[1] = "aball";
etc...

it will add more text to the list, like

car
ball
apple
bird
0=mycar
1=aball

This is not what I want. I don't want the extra text to add to the list. So, how can I add values to each text properly, and get the value?

A: 

hold a list(vector/array whatever you want) containing the name and value pairs. When selecting a name look the value up in the list.

PoweRoy
A: 

If you want to store the values in the ComboBox itself, then you need to use the Objects[] property instead of the Values[] property, for example:

ComboBox1->Items->Objects[0] = (TObject*) new String("mycar");
ComboBox1->Items->Objects[1] = (TObject*) new String("aball");
...
String value = * (String*) ComboBox1->Items->Objects[ComboBox1->ItemIndex];
...
delete (String*) ComboBox1->Items->Objects[0];
delete (String*) ComboBox1->Items->Objects[1];

As you can see, this requires managing dynamically allocated String objects. A better option would be to store the values in a separate list, such as a TStringList or std::vector, like PoweRoy suggested. As long as that list has the same number of items as the ComboBox, you can use ComboBox indexes to access the values, for example:

TStringList *MyValues = new TStringList;
...
MyValues->Add("mycar");
MyValues->Add("aball");
...
String value = MyValues->Strings[ComboBox1->ItemIndex];
...
delete MyValues;

Or:

#include <vector>

std::vector<String> MyValues;
...
MyValues.push_back("mycar");
MyValues.push_back("aball");
...
String value = MyValues[ComboBox1->ItemIndex];
...
Remy Lebeau - TeamB
A: 

and if you need to show the data from a database field? How to put in combobox?

tiago