微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 中的默认方法创建的绑定的情况。但是,实时绑定足够复杂,可以支持不存在这种对应关系的情况,在这种情况下,不应假设此答案中的方法会起作用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。