[英]Delphi 10.4 - Sort Memtable by clicking Stringgrid Header
我覺得自己像個白痴,因為我的問題看起來很簡單,但我沒有完成:D
我的設置是:
一個數據集(Memtable),一個字符串網格。 Grid 通過 live Bindungs 綁定。
我想通過單擊 GridHeader 對我的列進行排序。 在 OnHeaderClick 事件中,我得到一個 tColumn Object。 我只能讀取 Column.Header 字符串,但我將文本從 Header 更改為更易讀的文本。 當我將 Column.header 放入 Memtable.Indexfieldsname Memtable 時說該字段不存在,這是對的,但我不知道如何從列中獲取正確的字段名。
你想要做的很簡單。 在下面的示例中,它使用來自 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 中的默認方法創建的綁定的情況。 但是,實時綁定足夠復雜,可以支持不存在這種對應關系的情況,在這種情況下,不應假定此答案中的方法有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.