Johny
Johny

Reputation: 419

Altering ITEMINDEX of TComboBox does not trigger it's OnChange event

When programmatically changing the value of ItemIndex of a TComboBox component in Delphi, one would expect for the corresponding OnChange event to get triggered.

Afterall, the visible value of the ComboBox get's changed as a result. Strangely it does not. Same behavior in Delphi6, Delphi 2010 and Delphi XE7.

Is there any reason behind this behavior or it's just a pending bug?

Upvotes: 2

Views: 2634

Answers (3)

Tom Brunberg
Tom Brunberg

Reputation: 21045

As others have answered, it is as designed. You can, however, achieve the functionality you are missing by overriding the SetItemIndex() procedure as follows:

type
  TComboBox = class(Vcl.StdCtrls.TComboBox)
    procedure SetItemIndex(const Value: Integer); override;
  end;

  TForm3 = class(TForm)
    ...


implementation

procedure TComboBox.SetItemIndex(const Value: Integer);
begin
  inherited;
  if Assigned(OnSelect) then
    OnSelect(self);
end;

As you see I activate the OnSelect event instead of OnChange, because OnSelect is the one fired when you select an item from the dropdown list. You can, if you like, just as well use the OnChange event instead.

Upvotes: 4

LU RD
LU RD

Reputation: 34919

From documentation:

Occurs when the user changes the text displayed in the edit region.

Write an OnChange event handler to take specific action immediately after the user edits the text in the edit region or selects an item from the list. The Text property gives the new value in the edit region.

Note: OnChange only occurs in response to user actions. Changing the Text property programmatically does not trigger an OnChange event.

Since there is no editing done, this means that programmatically changing the ItemIndex does not trigger the OnChange event.

Upvotes: 7

Dalija Prasnikar
Dalija Prasnikar

Reputation: 28511

That is designed behavior. OnChange event is triggered only by user actions and not programatically.

OnChange Event

Occurs when the user changes the text displayed in the edit region. Write an OnChange event handler to take specific action immediately after the user edits the text in the edit region or selects an item from the list. The Text property gives the new value in the edit region.

Note: OnChange only occurs in response to user actions. Changing the Text property programmatically does not trigger an OnChange event.

Upvotes: 2

Related Questions