Sort a grid using a memory table

I want to sort the grid. I created a memory table and bound it to the grid as a data source. I am inserting data into a memory table from an nxQuery object. For sorting, I have to add an index also to the memory table.

This is adding and adding an index, which is in the form of 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 I'm trying to sort the memory table

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

but it does not work. when I click the button, it says: "There is no index for the field" firstname ""

+5
source share
1 answer

This works with the standard TClientDataSet.

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

 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; 

Launching the application and clicking on any of the column names immediately sorts the DBGrid by this column (if it is not already sorted by this column).

+4
source

Source: https://habr.com/ru/post/1243719/


All Articles