You can easily easily change the dataset shown by DBGrid at runtime. There are two approaches:
1: use one data source assigned to DBGrid.DataSource, and change the DataSource.DataSet to the desired DataSet. Here is a simple example with all the assignments made at runtime.
procedure TForm1.FormCreate(Sender: TObject); begin DBGrid1.DataSource := DataSource1; DataSet1.Active := true; DataSet2.Active := true; DataSet3.Active := true; end; procedure TForm1.Button1Click(Sender: TObject); begin DataSource1.DataSet := DataSet1; end; procedure TForm1.Button2Click(Sender: TObject); begin DataSource1.DataSet := DataSet2; end; procedure TForm1.Button3Click(Sender: TObject); begin DataSource1.DataSet := DataSet3; end;
2: use a DataSource for each DataSet and change DBGrid.DataSource to the desired data source. Here is a simple example with all the assignments made at runtime.
procedure TForm1.FormCreate(Sender: TObject); begin DataSource1.DataSet := DataSet1; DataSource2.DataSet := DataSet2; DataSource3.DataSet := DataSet3; DataSet1.Active := true; DataSet2.Active := true; DataSet3.Active := true; end; procedure TForm1.Button1Click(Sender: TObject); begin DBGrid1.DataSource := DataSource1; end; procedure TForm1.Button2Click(Sender: TObject); begin DBGrid1.DataSource := DataSource2; end; procedure TForm1.Button3Click(Sender: TObject); begin DBGrid1.DataSource := DataSource3; end;
If you define DBGrid columns, the DataSets structure must be the same, or you will have to change the column definitions when changing the displayed dataset.
I prefer to use a DataSource for each dataset because it is more flexible.
source share