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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With