Answer the question
In order to leave comments, you need to log in
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.
procedure TFormMain.FormCreate(Sender: TObject);
begin
DBGrid1.DataSource.DataSet.AfterScroll := GetIdFromSelectedRow;
end;
Answer the question
In order to leave comments, you need to log in
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.
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question