-1

I am trying to set a ComboBox's text conditionally - that is, if the text I am setting it to exists in the box's Items, then set it to that. Otherwise, leave it blank.

e.x.

ComboBox's Items:

  • Green
  • Blue
  • Pink
  • Red

For ComboBox1 I am trying to set to "Red". Because that string exists in the Items, the text property is set to "Red". For ComboBox2 I am trying to set to "Yellow", which doesn't exist, so I want that text empty (but the previous items still are there).

All the comboboxes will have the same Items. However, there are lots of combo's so I'm trying to avoid looping through each boxes owns items and compare each one. In C# you could just do something like:

ComboBox1.ItemIndex := 'My Text';

Which doesn't compile here.

ikathegreat
  • 2,311
  • 9
  • 49
  • 80

1 Answers1

1

You could use either

ComboBox1.ItemIndex := ComboBox1.Items.IndexOf('My Text');

or

ComboBox1.Text := 'My Text';

The second version requires that you have ComboBox's Style set to csDropDownList (otherwise the string would be shown in the combobox even if it is not in the list).

ain
  • 22,394
  • 3
  • 54
  • 74
  • 2
    That's what I thought too, but it ain't working with `csDropDownList`. See [Default Combo Box Behaviour](http://msdn.microsoft.com/en-us/library/windows/desktop/bb775793(v=vs.85).aspx#default_behavior) for WM_SETTEXT: _In drop-down list boxes, the window procedure returns CB_ERR._ – NGLN Dec 21 '13 at 08:06
  • Hmm, I'm pretty sure I have used it that way and it worked... must check tonight. Perhaps I used some custom CB which worked but I don't think so. Anyway, the first suggestion should work. – ain Dec 21 '13 at 08:54