User6996
User6996

Reputation: 3003

how to get ComboBox items count

I'm trying to get an combobox items count using the following code. It doesn't give an error nor the the right amount of count. I guess I have to convert int to string, but how?

ComboBox1->ItemIndex = 1;
int count = ComboBox1->Items->Count;
Edit1->Text =  "Count: " + count;

Upvotes: 1

Views: 8760

Answers (4)

Sangram Shinde
Sangram Shinde

Reputation: 11

There is no any need to go through all this jugglery. A simple function is available for that.

int count = ComboBox1.GetItemCount();

Upvotes: 1

azzyloth
azzyloth

Reputation: 43

ComboBox1->ItemIndex = 1; 
int count = ComboBox1->Items->Count;
Edit1->Text =  "Count: " + count;

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145419

ComboBox1->ItemIndex = 1;
int count = ComboBox1->Items->Count;
Edit1->Text =  "Count: " + count;

Here "Count: " + count is an expression where "Count: " decays to pointer to first element of the string, count is added to that pointer, with the result that it either points somewhere within the string (OK) or off the end of the string (generally Undefined Behavior).

Regarding the use of your ComboBox1, you haven't shown its declaration, and you haven't mentioned which GUI framework, if any, you're using.

So nothing can be said about it without guessing what it is.

In order to create formatted text with inserted textual value presentations, you can use e.g. a std::ostringstream from the <sstream> header, like this:

std::ostringstream stream;
stream << "Count: " << count;
Edit1->text = stream.str().c_str();

The call to .c_str() may or may not be necessary, depending on what Edit1.text accepts.

Upvotes: 3

mathematician1975
mathematician1975

Reputation: 21351

This line

 int count = ComboBox1->Items->Count; 

returns the numnber of string items in your TComboBox. You need to check this before setting

ComboBox1->ItemIndex = 1;

as ItemIndex is used to set the selected item in the combo box and is zero counted. To convert the integer to string in Embarcadero you can use IntToStr() function

Edit1->Text = "Count:" + IntToStr(count)

You will need #include "System.hpp" to access that function

Upvotes: 6

Related Questions