Title: How to sort DBGrid-Columns, create/delete secondary Indizes
Question: You will display data in DBGrid fields and allow it to sort
on any one of the columns by clicking on the column header.
Answer:
Try this little Sample to do this. You need this objects:
One TForm Form1
One TTable Table1 with connect to your table
One TDataSource DataSource1
One TDBGrid DBGrid1
Create secondary indizes for the wanted Tables-columns.
At program end you can destroy all this indizes.
To sort DBGrid-Columns click on the Column-name at the DBGrid-Title-Line.
The Title-Text-Fontstyle of the sorted Column is set to fsBold.
}
// Here create secondary indizes for the wanted Table-Fieldnames only:
procedure TForm1.FormCreate(Sender: TObject);
begin
// place here one call for every wanted secondary Index
CreateSX(Table1, 'FirstName');
CreateSX(Table1, 'SecondName');
CreateSX(Table1, 'Phone');
CreateSX(Table1, 'BirthDate');
// ... and so on
Table1.open;
end;
// Here delete all secondary Indizes at Application-Exit if you want:
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Table1.Close;
DeleteSX(Table1);
end;
// Here is the secondary-index create Procedure:
procedure TForm1.CreateSX(TableX: TTable; cFieldname: string);
begin
with TableX do begin
// table must be open with exclusive
Active := False;
Exclusive := True;
IndexDefs.Update;
Active := True;
// if Fieldname not exists create this secondary index new
if indexdefs.indexof(cFieldName) = -1 then begin
addindex(cFieldname, cFieldname, []);
end;
// close the table and reset exclusive
Active := false;
exclusive := False;
end;
end;
// Here is the secondary-index delete Procedure:
procedure TForm1.DeleteSX(TableX: TTable);
var
I: Integer;
begin
TableX.active := False;
TableX.IndexDefs.update;
// Look for all Indizes
for I := TableX.IndexDefs.Count - 1 downto 0 do begin
// ignore primary Index
if (TableX.IndexDefs.Items[I].options * [ixPrimary]) ([ixPrimary]) then
// This is an secondary index. Delete it.
TableX.DeleteIndex(TableX.IndexDefs.Items[I].fields);
end;
end;
// Here is the Procedure to sort the DBGrid-Columns:
procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var
I: Integer;
begin
Table1.IndexDefs.Update;
// if an index exist for this column then change it
if Table1.indexdefs.indexof(column.FieldName) 0 then begin
Table1.IndexFieldNames := Column.Fieldname;
with TDBGrid(Column.Grid) do begin
for I := 0 to Columns.Count - 1 do begin
// change also the associated titletext fontstyle
if Columns[I] = Column then
Columns[I].Title.Font.Style := Columns[I].Title.Font.Style + [fsBold]
else
Columns[I].Title.Font.Style := Columns[I].Title.Font.Style - [fsBold];
end;
end;
end;
end;