当前位置: 动力学知识库 > 问答 > 编程问答 >

delphi - Dual ComboBox selection dependency

问题描述:

I would like to have a 2 drop down combobox with the following items:

  • Combo1:

    Pets

    Fruits.

  • Combo2:

    If Pets is picked then combobox2items.Add:

    Dog, Cat, Chicken

If Fruits is picked then combobox2items.Add:

Melon, Orange, Apple

So I try to do this:

procedure TForm1.FormCreate(Sender: TObject);

begin

ComboBox1.Items.Add('Pets');

ComboBox1.Items.Add('Fruits');

end;

procedure TForm1.ComboBox2Change(Sender: TObject);

begin

if ComboBox1.ItemIndex = 1) then

ComboBox2.Items.Add('Dog');

ComboBox2.Items.Add('Cat');

ComboBox2.Items.Add('Chicken');

if ComboBox1.ItemIndex = 2) then

ComboBox2.Items.Add('Melon');

ComboBox2.Items.Add('Orange');

ComboBox2.Items.Add('Apple');

end;

My code is not working. How to figure this out in simple way?

网友答案:

You need to use begin..end like this:

if ComboBox1.ItemIndex = 1 then
begin 
  ComboBox2.Items.Add ('Dog');
  ComboBox2.Items.Add ('Cat'); 
  ComboBox2.Items.Add ('Chicken');
end;

if ComboBox1.ItemIndex = 2 then 
begin
  ComboBox2.Items.Add ('Melon');
  ComboBox2.Items.Add ('Orange'); 
  ComboBox2.Items.Add ('Apple');
end;

Also you need to clear the combobox before adding in the new items;

网友答案:

When it comes to Combo Box dependencies, I like to build a Dictionary that represents these dependencies. Basically, you have your Dictionary keep the items of ComboBox1 as keys. When ComboBox1 changes, you re-assign ComboBox2's Items property to the StringList behind the selected Key. This saves you the trouble of removing/adding individual strings every time ComboBox1's index is changed.

procedure TForm1.FormCreate(Sender: TObject);
begin
  FComboBoxDependencies := TDictionary<string,TStringList>.Create;

  FComboBoxDependencies.Add('Pets',TStringList.Create);
  FComboBoxDependencies['Pets'].Add('Dog');
  FComboBoxDependencies['Pets'].Add('Cat');
  FComboBoxDependencies['Pets'].Add('Chicken');

  FComboBoxDependencies.Add('Fruit',TStringList.Create);
  FComboBoxDependencies['Fruits'].Add('Orange');
  FComboBoxDependencies['Fruits'].Add('Apple');
  FComboBoxDependencies['Fruits'].Add('Melon');

  //Trigger Change Event at start to display the selected Key
  ComboBox1Change(self);
end;

procedure TForm1.ComboBox1Change(Sender: TObject);
begin
  ComboBox2.Items := FComboBoxDependencies[ComboBox1.Text];   //Grab Items to be displayed from dictionary
  ComboBox2.ItemIndex := 0;          //Set Itemindex to 0 to show first item
end;

Of course, this can be refined and tweaked to be more reliable, but the core of this works pretty good.

分享给朋友:
您可能感兴趣的文章:
随机阅读: