【问题标题】:Delphi 10.4 - Sort Memtable by clicking Stringgrid HeaderDelphi 10.4 - 通过单击 Stringgrid Header 对 Memtable 进行排序
【发布时间】:2021-06-01 14:58:23
【问题描述】:

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

我的设置是:

一个数据集(Memtable),一个字符串网格。 Grid 通过 live Bindungs 绑定。

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

【问题讨论】:

  • 您需要找到绑定到您要排序的StringGrid列的MemTable FieldName(您必须知道从将网格绑定到MemTable时的FieldName),然后设置MemTable的IndexFieldNames财产。就是这样。
  • @MartynA 感谢您的回复。但这正是缺少的部分。我不知道如何找到绑定到 StringGrid 的 MemTable 字段名。使用 Column.Index 在数据集中获取我的字段是解决方案!

标签: delphi firemonkey tstringgrid fdmemtable


【解决方案1】:

您想要做的事情很简单。在下面的示例中,它使用了来自的演示数据 在 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 中的默认方法创建的绑定的情况。但是,Live Binding 足够复杂,可以支持不存在这种对应关系的情况,在这种情况下,不应假定此答案中的方法有效。

【讨论】:

  • 从列索引中获取我的数据集字段是缺少的链接。非常感谢您的帮助。
猜你喜欢
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-08
  • 2011-10-10
相关资源
最近更新 更多