Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort grid using memory table

Tags:

delphi

I want to sort a grid. I created a memory table and link it to the grid as the data source.I am inserting data to the memory table from a nxQuery object. For the sorting i have to add index as well to the memory table.

This is the index adding and inserting part which is in the form create event

nxMemTable1.IndexDefs.Clear;
nxMemTable1.FieldDefs.Clear;

nxMemTable1.FieldDefs.Add('packpatientid', ftInteger, 0, False);
nxMemTable1.FieldDefs.Add('firstname', ftString, 10, False);
nxMemTable1.FieldDefs.Add('lastname', ftString, 10, False);
while not nxQuery1.EOF do
begin
  nxMemTable1.Append;
  nxMemTable1.FieldByName('packpatientid').AsInteger :=   nxQuery1packpatientid.AsInteger;
  nxMemTable1.FieldByName('firstname').AsString := nxQuery1firstname.AsString;
  nxMemTable1.FieldByName('lastname').AsString := nxQuery1lastname.AsString;
  nxMemTable1.Post;
end;

and this is the code that i am trying to sort the memory table

procedure TForm1.Button2Click(Sender: TObject); begin nxMemTable1.IndexFieldNames := 'firstname'; end;

but this is not working. when i click the button it says "No index for field 'firstname'"

like image 333
Ishanka Avatar asked Sep 25 '22 07:09

Ishanka


1 Answers

This works with the standard TClientDataSet.

I created a new VCL Forms project, dropped a TClientDataSet on the form, and named it CDS for simplicity in the code. I then added a TDataSource, assigned CDS to its DataSet property, added a TDBGrid, and assigned DataSet1 as its DataSource. I then created two event handlers, one for the Form1.OnCreate event and one for the DBGrid1. OnTitleClick event.

procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var
  sField: string;
begin
  sField := Column.FieldName;
  if sField <> CDS.IndexFieldNames then
    CDS.IndexFieldNames := sField;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CDS.FieldDefs.Add('LastName', ftString, 30);
  CDS.FieldDefs.Add('FirstName', ftString, 30);
  CDS.FieldDefs.Add('ID', ftInteger);
  CDS.CreateDataSet;
  CDS.AppendRecord(['Smith', 'John', 3]);
  CDS.AppendRecord(['Doe', 'Jane', 1]);
  CDS.AppendRecord(['Adams', 'Quincy', 2]);
  CDS.IndexFieldNames := 'LastName';
end;

Running the application and clicking on any of the column titles immediately sorts the DBGrid by that column (if it's not already sorted by that column).

like image 61
Ken White Avatar answered Sep 28 '22 03:09

Ken White