1

I have a trouble with SetCurSel of MFC.

My combobox has data like this: a, b, c, shop10, shop1, c, d.

I add data for combobox like that, then set cursel is Shop1

m_cbb.AddString(_T("a"));
m_cbb.AddString(_T("b"));
m_cbb.AddString(_T("shop10"));
m_cbb.AddString(_T("shop1"));
m_cbb.AddString(_T("c"));
m_cbb.AddString(_T("d"));

//m_cbb.SetWindowText(_T("shop1"));
m_cbb.SetCurSel(3);
UpdateData(FALSE);

It show Shop1 correct, but when I show combobox, cursel is Shop10.

Cursel incorrect

What is my mistake?

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • Welcome to Stack Overflow. You should add more details to your question and *show your code as text, not as an image*. But, from what I can see, the dropdown selection is being set to the first match for the current edit selection, and "shop1" matches the first part of the "shop10" string. – Adrian Mole May 13 '21 at 03:18
  • Thanks for your help, I have edited my question, is there anyway to cursel at Shop1 in that case? –  May 13 '21 at 03:51
  • 2
    The interesting thing about combo boxes is that the text need have no relation to the items in the list, unless you use the `CBS_DROPDOWNLIST` style. – Mark Ransom May 13 '21 at 04:17
  • Oh, I changed combobox style to CBS_DROPDOWNLIST and it's fixed my problem. Thanks so much for your help. –  May 13 '21 at 04:43
  • It is also a flaw in the combo boilerplate code. The way it is designed means that it selects the first match (and shop1 is first matched my shop10 in the list), Something you need to be aware of at times. – Andrew Truckle May 13 '21 at 07:43
  • 1
    If you want to select the item which text is "Shop1", you will need to do: `int index = m_cbb.FindStringExact(L"Shop1"); if (index != CB_ERR) m_cbb.SetCursel(index);` – sergiol May 13 '21 at 16:41

0 Answers0