I'm just beginning to learn Delphi and I've a problem. I'd refresh DBGrid from another form. My code:
Form1:
unit uForm1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, Grids, DBGrids, StdCtrls;
type
TForm1 = class(TForm)
btnAdd: TButton;
grid: TDBGrid;
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
procedure btnAdd(Sender: TObject);
private
public
constructor Create(Owner:TComponent); overload;
end;
var
form1: TForm1;
implementation
uses uForm2, uDbOperations;
{$R *.dfm}
procedure TForm1.btnAddClick(Sender: TObject);
var
frm : TForm2;
begin
frm := TForm2.Create(form1);
frm.ShowModal;
frm.Free;
end;
Form2:
unit uForm2;
procedure TForm2.btnAddClick(Sender: TObject);
var
query : string;
begin
query := 'Insert into Employees(Name) Values('''+txtName.Text+''');';
DbOperations.InsertOrUpdate(query, ADOQuery1);
ModalResult := mrCancel;
//And this here I'd refresh grid on form1
end;
end.
How I can after add record in form2, refresh dbgrid in form1? I've tried many ways, but without success. I know that in C# need pass reference in constructor, but delphi how?
Using your pattern, I would do something like this:
procedure TForm1.btnAddClick(Sender: TObject);
var
frm : TForm2;
begin
frm := TForm2.Create(form1);
try
if frm.ShowModal = mrOK then
begin
Grid.Datasource.Dataset.Refresh;
// some databases require open/close to refresh
// in this case Grid.Datasource.Dataset.close;
// Grid.Datasource.Dataset.Open;
end;
finally
frm.Free;
end
end;
procedure TForm2.btnAddClick(Sender: TObject);
var
query : string;
begin
query := 'Insert into Employees(Name) Values('''+txtName.Text+''');';
DbOperations.InsertOrUpdate(query, ADOQuery1);
ModalResult := mrOK;
// let a cancel button on Form2 perform ModalResult = mrCancel
// to avoid unnecessary dataset refreshes..
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With