Mega Code Archive
How to load a StringGrid with a Query Result
Title: How to load a StringGrid with a Query Result
Question: You can always use a DBGrid to display a Query Result, but if you dont need the overhead of data aware components, you can use the following function to populate a StringGrid with the result of a SQL sentence.
Answer:
Procedure QueryGrid(DBName, Statement: String; Target: TStringGrid; Titles: Boolean);
Var Col, Lin: Integer;
begin
With TQuery.Create(Nil) Do
Try
DatabaseName := DBName;
SQL.Text := Statement;
Open;
If Not IsEmpty Then
Begin
Target.ColCount := FieldCount;
Target.RowCount := RecordCount+ IIF(Titles,1,0);
Target.FixedCols := 0;
Target.FixedRows := IIF(Titles,1,0);
If Titles Then
For Col := 0 To FieldCount-1 Do
Target.Cells[Col,0] := Fields[Col].FieldName;
Lin := 0;
While Not Eof Do
Begin
For Col := 0 To FieldCount-1 Do
Target.Cells[Col,Lin+Target.FixedRows] :=
Fields[Col].AsString;
Next;
Inc(Lin);
End;
End;
Finally
Close;
Free;
End;
end; { QueryGrid }
This routine was provided by Norbert Landa Martinez.