user9374422
user9374422

Reputation: 11

VC++ MFC -> ComboBox, GetCurSel()?

Where am I going wrong? I have this code:

CComboBox m_item;

if((m_item.GetCurSel()) == atoi("TC001"))
    MessageBox(L"TC001");

if((m_item.GetCurSel()) == atoi("TC002"))
    MessageBox(L"TC002");

If I select "TC001" in the ComboxBox, it pops up both "TC001" and "TC002" message boxes.

If I select "TC002" in the ComboxBox, it doesn't show any MessageBox.

Why?

Upvotes: 0

Views: 1769

Answers (2)

acraig5075
acraig5075

Reputation: 10756

Looks like you want to compare the selected text, and not the selected item number. To do that use CComboBox::GetLBText().

CStringW text;
m_item.GetLBText(m_item.GetCurSel(), text);

if (text == L"TC001")
    MessageBox(L"TC001");
else if (text == L"TC002")
    MessageBox(L"TC002");

Upvotes: 3

IInspectable
IInspectable

Reputation: 51511

From the documentation of atoi:

Interprets an integer value in a byte string pointed to by str.

Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts:

  • (optional) plus or minus sign
  • numeric digits

[...] If no conversion can be performed, ​0​ is returned.

The strings "TC001" and "TC002" cannot be converted to an integer, thus the call to atoi returns 0 in both cases.

CComboBox::GetCurSel returns

the zero-based index of the currently selected item in the list box of a combo box [...]

Thus, if the item with display string "TC001" is the first item, GetCurSel returns 0, the same value returned by atoi on non-integer input. Both comparisons return true, so both message boxes are shown.

The solution is two-fold:

  • Learn how to use a debugger.
  • Don't use string comparisons or conversions to determine the selected value. Instead use the positional index, or attach custom data to each item. This requires either calling CComboBox::SetItemData, or switching to a CComboBoxEx class that provides the InsertItem member, so you can pass a COMBOBOXITEM structure and use its lParam member.

Upvotes: 3

Related Questions