ricardomenzer
ricardomenzer

Reputation: 270

How to get ComboBox ItemIndex before OnChange event?

I have a TComboBox in my Delphi 7 form with some Items in it. In the OnChange event, I do some processing depending on what Item was selected, but during this processing I may want to revert to the previous selected Item.

Programmatically, I want something like

ComboBox.ItemIndex := oldItemIndex;

The problem is I don't know how to get the oldItemIndex.

I tried defining a (global) variable in the OnCloseUp event, but ItemIndex there is already the new selected ItemIndex. I also tried saving oldItemIndex on OnEnter event. While this works for saving the oldItemIndex the first time the control gets focused, it does not works if the focus is kept in it, thus effectively only working the first time the item changes.

What's the easiest way to get the last selected item in a ComboBox when inside the OnChange event handler?

Upvotes: 2

Views: 6328

Answers (1)

GuidoG
GuidoG

Reputation: 12039

one way to do this is like this :

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    Edit1: TEdit;
    procedure ComboBox1Change(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    FPriorIndex : integer;
  public
  end;

implementation

{$R *.dfm}

procedure TForm1.ComboBox1Change(Sender: TObject);
begin
  showmessage(ComboBox1.Items[FPriorIndex]);
  FPriorIndex := ComboBox1.ItemIndex;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox1.ItemIndex := 0;
  FPriorIndex := ComboBox1.ItemIndex;
end;

How to do it without variable outside the OnChange event:

procedure TForm1.ComboBox1Change(Sender: TObject);
const
  PRIOR_INDEX : integer = 0;
begin
  showmessage(ComboBox1.Items[PRIOR_INDEX]);
  PRIOR_INDEX := ComboBox1.ItemIndex;
end;

For this to work you need to open your project options / Compiler and check "Assignable typed constants"

Upvotes: 10

Related Questions