Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi7, create combobox items

I would like to give the user a variety of options using combobox. So there are 2 combobox. The 1st one has about 5 options, the second ones items will be created based on what the user will choose at the 1st combobox.

So far, I have tried this: Combobox2.Items.Strings[1]:='xxxx' which appears me this error:

List out of Bound.

What should I do?

like image 400
user2296565 Avatar asked Oct 22 '22 10:10

user2296565


1 Answers

To populate a TComboBox at runtime, you can do like this [1]:

ComboBox1.Items.BeginUpdate;
try
  ComboBox1.Items.Clear;
  ComboBox1.Items.Add('Alpha');
  ComboBox1.Items.Add('Beta');
  ComboBox1.Items.Add('Gamma');
  ComboBox1.Items.Add('Delta');
finally
  ComboBox1.Items.EndUpdate;
end;

You can also assign a pre-fabricated TStringList to it:

ComboBox1.Items.Assign(MyStringList);

[1]:

The try..finally part is important, because, without it, if an exception is raised and not handled between BeginUpdate and EndUpdate, the combobox will remain ("get stuck") in its "updating" state and so will malfunction from that point on.

Of course, in this trivial example, the risk of an exception is minute, but in other cases it can be significant. And the code might change: you might add a ComboBox1.Items.Add(MightRaise()) or an if MightRaise() then ComboBox1.Items.Add('Epsilon') in the future.

At any rate, you want code that works in 100 % of all cases, not 99.9 %. Also, the above pattern is easily recognized and at least to me aids in the understanding of the code. If you always use the same patterns, the code becomes easier to parse mentally.

like image 159
Andreas Rejbrand Avatar answered Oct 30 '22 18:10

Andreas Rejbrand