S
S
sorry_i_noob2019-06-23 15:35:02
Delphi
sorry_i_noob, 2019-06-23 15:35:02

Why does the code work on an event - a button click. But it doesn't work on the event - form creation?

There is such a code.

unit UnitMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids,
  DBConnection, Vcl.StdCtrls;

type
  TFormMain = class(TForm)
    DBGrid1: TDBGrid;
    SelectedId: TLabel;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure GetIdFromSelectedRow(DataSet: TDataSet);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  FormMain: TFormMain;

implementation

{$R *.dfm}

procedure TFormMain.Button1Click(Sender: TObject);
begin
  DBGrid1.DataSource.DataSet.AfterScroll := GetIdFromSelectedRow;
end;

procedure TFormMain.FormCreate(Sender: TObject);
begin
  DBGrid1.DataSource.DataSet.AfterScroll := GetIdFromSelectedRow;
end;

procedure TFormMain.GetIdFromSelectedRow(DataSet: TDataSet);
begin
  SelectedId.Caption := DataSet.FieldByName('id').AsString;
end;

end.

It gives the following error:
5d0f6ef3022af919991346.png
If you do not comment out the action when creating the form:
procedure TFormMain.FormCreate(Sender: TObject);
begin
  DBGrid1.DataSource.DataSet.AfterScroll := GetIdFromSelectedRow;
end;

But when the button is clicked, this code works and doesn't throw any error.
Why is that? I need to execute this code at application startup. How to get around this error? I tried sleep but it didn't help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kalapanga, 2019-06-23
@sorry_i_noob

The form and, accordingly, the components on it have not yet been created. DBGrid1 does not yet exist when you try to access it. Try using the form's OnShow event.

K
Konstantin Tsvetkov, 2019-06-23
@tsklab

type
  TFormMain = class(TForm)
    DBGrid1: TDBGrid;
    DBText1: TDBText;
    procedure FormCreate(Sender: TObject);
  private    { Private declarations }
  public    { Public declarations }
  end;

var
  FormMain: TFormMain;

implementation

{$R *.dfm}

procedure TFormMain.FormCreate(Sender: TObject);
begin
  DBText1.DataSource := DBGrid1.DataSource;
  DBText1.Field := DBGrid1.DataSource.DataSet.FieldByName('id')
end;

end.

I
Igor, 2019-06-25
@IgorPI

When creating objects, pay attention to the application life cycle.
For example, your error says that the object does not exist yet. But you call its methods / properties.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question