How to use TADODataset, TDatasource and TDBGrid in Delphi XE2?
Below is the code snippet in Delphi XE2 to demonstrate the use of TADODataset, TDatasource and TDBGrid. The code fetches the data in dataset and then assigns that dataset to datasource and further that datasource is assigned to datagrid.
procedure TClass.PopulateGrid(aField: integer);
begin
try
with dsMyADODataSet do
begin
Close;
Connection := connMyADOConnection;
CommandType := cmdText;
CommandText := 'SELECT * FROM myTable WHERE fieldA = :fieldA ';
Parameters.ParamByName('fieldA').Value := aField;
Open;
dsMyDataSource.DataSet := dsMyDataSet;
dgrMyDBGrid.DataSource := dsMyDataSource;
end;
except
on E : Exception do
begin
ShowMessage('Error occured in function PopulateGrid: ' + E.Message);
exit;
end;
end;
end;
begin
try
with dsMyADODataSet do
begin
Close;
Connection := connMyADOConnection;
CommandType := cmdText;
CommandText := 'SELECT * FROM myTable WHERE fieldA = :fieldA ';
Parameters.ParamByName('fieldA').Value := aField;
Open;
dsMyDataSource.DataSet := dsMyDataSet;
dgrMyDBGrid.DataSource := dsMyDataSource;
end;
except
on E : Exception do
begin
ShowMessage('Error occured in function PopulateGrid: ' + E.Message);
exit;
end;
end;
end;
Explanation: ADOConnection is set to dsMyADODataset. Then CommandType and CommandText are assigned to the dataset. Then this dataset is assigned to the datasource and then that datasource is assigned to the datagrid.