How to dynamically link different tables to a stringGrid?

As title suggested, I have a design time StringGrid placed on the form. I need to change the name of the Table of a Database, then linked to a stringGrd via livebinding.
When first run, everything worked ok. When the name of the table changes, same code will be excuted again. But complained “Comlumn index, -1, out of boundary”

What shall I do in this case?

Another question, the commented line

// if  Assigned (LGTDS_BindSourceDB_Temp)     then

It should return false during first run, but I got a true. Anyone know why?
Delphi 11/Windows 11.

    procedure TForm1.LB_TableNamesItemClick(const Sender: TCustomListBox; const Item: TListBoxItem);

var

  BindSourceDB_temp : TBindSourceDB;
  LGTDS_BindSourceDB_Temp : TLinkGridToDataSource;

begin
  DM1.UT_Local.connection:=DM1.UC_Local;
  DM1.UT_Local.tablename:=Item.Text;

 // if  Assigned (LGTDS_BindSourceDB_Temp)     then
 // if  LGTDS_BindSourceDB_Temp.Active then LGTDS_BindSourceDB_Temp.Active  :=false;

  with DM1 do begin
  UT_Local.Close;
  UT_Local.tablename:=  Item.Text;
  UT_Local.Open;
  BindSourceDB_temp := TBindSourceDB.Create(Self);
  BindSourceDB_temp.DataSet := UT_Local;
  LGTDS_BindSourceDB_Temp := TLinkGridToDataSource.Create(Self);
  LGTDS_BindSourceDB_Temp.DataSource := BindSourceDB_temp;
  LGTDS_BindSourceDB_Temp.GridControl := SG_Table1;
  LGTDS_BindSourceDB_Temp.Active:=true;


  end;

Leave a Comment