TAdvStringGrid

Example 17 : using ADO to load data into TAdvStringGrid

This simple procedure shows how to use ADO to load data from a table in a MS Access database. To open a table from a SQL server database in a grid, change the open line to use the SQL server. Be sure to use the unit COMOBJ for this code.

procedure LoadFromADO(sg: tadvstringgrid; mdb, table: string);
var
  adoset:variant;
  adoconn:variant;
  adofield:variant;
  i,j:integer;

begin
  adoconn := CreateOLEObject('ADODB.Connection');
  adoconn.Open('driver={Microsoft Access Driver (*.mdb)};dbq='+mdb);

  adoset := adoconn.Execute('SELECT * FROM '+table);

  sg.colcount := adoset.fields.count + 1;

  for i:=1 to adoset.fields.Count-1 do
  begin
    adofield:=adoset.fields.item(i);
    sg.cells[i,0]:=adofield.Name;
  end;

  j := 1;
  while not adoset.EOF do
  begin
    if (j>sg.rowcount) then 
      sg.rowcount := sg.rowcount + 1;
    for i := 1 to adoset.fields.Count-1 do
    begin
      adofield := adoset.fields.item(i);
      sg.cells[i,j] := adofield.Value;
    end;
    adoset.MoveNext;
    inc(j);
  end;
  adoset := unassigned;
end;


Delphi project & source files for downloading included in the main demos distribution for Delphi.