簡體   English   中英

在Delphi中重新定位DBGrid中的列

[英]Repositioning columns in DBGrid in Delphi

我需要動態更改DBGRid中某些列的位置。 假設我需要將第21列放在位置10。我使用:

DBGrid.Columns[21].Index:=10;

但是,這也改變了數組本身,這意味着,下次我要訪問此列時,我將需要編寫DBGrid.Columns [10],這有點不干凈,我需要記住所有列的位置,等等。 。有沒有更簡單的方法來重新定位列? 如果在此位置更改期間數組索引不更改也將是很好的。

解決該問題的一種簡單方法是不按索引訪問列,而按字段名訪問列。 介紹一個這樣的方法:

function GetColumn(aGrid : TDBGrid; aFieldName : string) : TColumn;
var
  I : integer;
begin
  for I := 0 to DBGrid.Columns.Count-1 do
    if aDBGrid.Columns[I].FieldName = aFieldName then
    begin
      Result := aDBGrid.Columns[I];
      exit;
    end;
  Result := nil;
end;

缺點是您每次需要訪問網格時都必須運行循環,這會導致較小的延遲,因此,如果速度至關重要,則可以考慮使用其他選項。

你是對的。 您必須跟蹤列的位置。 也許在單獨的結構中,或者作為從TCustomGrid派生的后代對象。

我保留了一個容器對象,除其他事項外,我還在其中存儲列的大小,它們包含的數據的類型,排序順序,格式設置選項以及網格中的位置。 然后,我有一個引用容器的自定義網格。

type
  TpaGrid = class;
  TpaColumnType = (ctText,ctDateTime,ctNumber,ctSize,ctPic,ctFileName);

  TpaColumn = class(TCollectionItem)
   private
    FCaption: string;
    FTitleFont: TFont;
    FTitleAlignment: TAlignment;
    FDataType : TPaColumnType;
    FWidth: Integer;
    FFont: TFont;
    FColor: TColor;
    FBackColor: TColor;
    FAltBackColor: TColor;
    FAlignment: TAlignment;
    FPosition : integer;
    FSortOrder : integer;   // 0=no sort, 1=first, 2=second, etc...
    FSortAscending : boolean;
    // .... and many other interesting attributes 
   public
    // ... published properties
 end;

 TpaColumnClass = class of TPaColumn;

 TpaColumns = class(TCollection)
  private
   FGrid: TPaGrid;
   // ... Getters and Setters, exposing the items as columns
  public
   constructor Create(grid:TPaGrid; ColumnClass: TPaColumnClass);
   function  AddColumn: TPaColumn;
   // ... Load and Save procedures
   // ... published properties
 end;

 TpaGrid = class (TStringGrid)
  // ... overriden methods WMSize, DrawCell, ...
  // ... getters and setters
  private
   FColumns : TpaColumns;
  // ... 

結束;

無論如何,對於那些到達此頁面的人(像我一樣),正在尋找一種方法來對網格中的列進行重新排序:

type
  THackAccess = class(TCustomGrid);

procedure TCustomGrid_MoveColumn(grid: TCustomGrid; fromCol, toCol: integer);
begin
  THackAccess(grid).MoveColumn(fromCol+1, toCol+1);
end;

輸入列從零開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM