Re: Delphi: sorting records from a DBgrid


[ Delphi Forum -- by DelphiLand ]

Posted by webmaster Guido on December 14, 2003 at 19:29:22:

In Reply to: Re: sorting record from a DBgrid posted by webmaster Guido on December 05, 2003 at 18:21:53:

: : 1.what coding procdure will i write to sort record say in a database of students where i want only female students from only the display records form the dbgrid and not from the table.

: ---------

: 1. Use a filter on the table if it's a small table or a local table.
: For a non-local table (network) or for a large table, better use a TQuery.

: I've sent you an e-mail for more details.
------------

Here's a solution for filtering the records (only female, only male, all records), according to what is selected in a combobox.
So I added a field SEX to table STUDENTS.DBF, that is set to 'F' or 'M'. On the students form, a combobox is added, and the following procedure is connected to its OnChange event:

procedure TFormStudents.ComboBox1Change(Sender: TObject);
begin
  if ComboBox1.Text = 'Female' then begin
    tStudents.Filter := 'Sex = ''F''';
    tStudents.Filtered := True;
  end
  else if ComboBox1.Text = 'Male' then begin
    tStudents.Filter := 'Sex = ''M''';
    tStudents.Filtered := True;
  end
  else
    tStudents.Filtered := False
end;

...or maybe you prefer this shorter version of the code:

procedure TFormStudents.ComboBox1Change(Sender: TObject);
begin
  tStudents.Filtered := (ComboBox1.Text = 'Female') or (ComboBox1.Text = 'Male');
  if ComboBox1.Text = 'Female' then
    tStudents.Filter := 'Sex = ''F'''
  else if ComboBox1.Text = 'Male' then
    tStudents.Filter := 'Sex = ''M''';
end;

I made the updates to the example project that I presented in a previous message. You can download from this password protected page:
http://www.festra.com/dclub
User name: dclub
Password: your membership access password


[ Delphi Forum ]
[ DelphiLand: free Delphi source code, tips, tutorials ]