2

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Johny
  • 419
  • 4
  • 15
  • 2
    I don't understand why people seem so reluctant to read the documentation. Is it because you don't know where it is? http://stackoverflow.com/questions/21403628/how-can-i-search-for-delphi-documentation – David Heffernan Jun 02 '16 at 08:44
  • Please accept my apologies @David Heffernan – Johny Jun 02 '16 at 08:49
  • Fwiw, I have always thought that the fact that this is "as designed" behaviour for many controls (esp. TPageControl) was a design mistake, because it necessitates coding that ought to be superfluous. – MartynA Jun 02 '16 at 09:35

3 Answers3

7

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.

Community
  • 1
  • 1
LU RD
  • 34,438
  • 5
  • 88
  • 296
4

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.

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
2

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.

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159