Delphi 10.4 - 通过单击 Stringgrid 标题对 Memtable 进行排序

问题描述

我觉得自己像个白痴,因为我的问题看起来很简单,但我没有完成:D

我的设置是:

一个数据集(Memtable),一个 Stringgrid。 Grid 通过实时 Bindungs 进行绑定。

我想通过单击 GridHeader 对我的列进行排序。在 OnHeaderClick 事件中,我得到一个 tColumn 对象。我只能读取 Column.Header 字符串,但我将文本从 Header 更改为更易于朗读的文本。当我将 Column.header 放入 Memtable.Indexfieldsname 时,Memtable 说该字段不存在,这是正确的,但我不知道如何从该列中获取正确的 Fieldname。

解决方法

你想要的很简单。在下面的示例中,它使用了来自 在 Biolife 演示中,我完全通过绑定对象将 StringgRid 链接到 FDMemTable 在代码中创建,以便对任何绑定步骤或绑定属性毫无疑问, 也不是用于建立绑定的方法。

procedure TForm2.FormCreate(Sender: TObject);
var
  BindSourceDB1 : TBindSourceDB;
  LinkGridToDataSourceBindSourceDB1 : TLinkGridToDataSource;
begin
  //  Note :  You need to load FDMemTable1 at design time from the sample Biolife.Fds datafile

  //  The following code creates a TBindSourceDB which Live-Binds FDMemTable1
  //  to StringGrid1
  //
  //  As a result,the column header texts will be the fieldnames of  FDMemTable1's fields
  //  However,the code that determines the column on which to sort the StringGrid does not depend
  //  on this

  BindSourceDB1 := TBindSourceDB.Create(Self);
  BindSourceDB1.DataSet := FDMemTable1;

  LinkGridToDataSourceBindSourceDB1 := TLinkGridToDataSource.Create(Self);
  LinkGridToDataSourceBindSourceDB1.DataSource := BindSourceDB1;
  LinkGridToDataSourceBindSourceDB1.GridControl := StringGrid1;

end;

procedure TForm2.StringGrid1HeaderClick(Column: TColumn);

//  Sorts the STringGrid on the column whose header has been clicked

var
  ColIndex,FieldIndex : Integer;
  AFieldName : String;
begin

  ColIndex := Column.Index;
  FieldIndex := ColIndex;

  AFieldName := FDMemTable1.Fields[FieldIndex].FieldName;
  Caption := AFieldName;

  //  Should check here that the the field is a sortable one and not a blob like a graphic field

  FDMemTable1.IndexFieldNames := AFieldName;
end;

请注意,此答案假定网格列和绑定数据集的字段之间存在一对一的对应关系,这通常是使用 IDE 中的默认方法创建的绑定的情况。但是,实时绑定足够复杂,可以支持不存在这种对应关系的情况,在这种情况下,不应假设此答案中的方法会起作用。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...