Re: DBGrid Sort on Runtime

Posted by webmaster Guido on October 07, 2000

In Reply to: DBGrid Sort on Runtime posted by Rafael Alvarez on October 06, 2000:

: Any of you can tell me how to sort a table on a dbgrid by clicking the column title?
: I need the event code for OnTitleClick.

Suppose that we want to show "articles" from a Paradox table called ART.DB. If your DataSet is a TQuery component, than the initial data are shown by:

procedure TForm1.FormCreate(Sender: TObject);
begin
  Query1.SQL.Clear;
  Query1.SQL.Add('select * from ART.DB');
   Query1.Open;
end;

Clicking on one of the columns title:

procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var
  OrderBy: string;
begin
  OrderBy := Column.FieldName;
  with Query1 do begin
    DisableControls;
    Close;
    SQL.Clear;
    SQL.Add('select * from ART.DB order by ' + OrderBy);
    Open;
    EnableControls;
  end;
end;

That's OK for relatively small tables. For larger tables, you use a TTable instead of a TQuery, with an index for every field (columnn) that is displayed. Showing the initial data:

procedure TForm1.FormCreate(Sender: TObject);
begin
  // At design time, the initial index is set as a property 
  // of Table1, the articles table 
  Table1.Open;
end; 

Clicking on one of the columns' title:

procedure TForm1.DBGrid1TitleClick(Column: TColumn);
begin
  with Table1 do begin
    if Column.FieldName = 'ID' then IndexName := 'ArtID'
    else if Column.FieldName = 'Name' then IndexName := 'ArtName'
    else // and so on...  
  end;
end; 

Related Articles and Replies: