2009-12-22 94 views
1

我需要动态地改变在某些DBGRID列的位置。比方说,我需要把列数21的位置10.我用:列重新定位在Delphi

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

但是,这也改变了数组本身,这意味着,下一次我要访问此专栏中,我将需要写DBGrid.Columns [10],这使得它有点不干净,我需要记住所有列等是否有重新定位的列作为一个更简单的方法的立场? 如果在此位置更改期间数组索引不改变,这也会很好。

回答

6

一个简单的方法来处理这个问题是不是指数,而是由字段名访问列。介绍一个方法是这样的:

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; 

的缺点是,你必须每次需要访问网格时运行的循环,造成延迟,所以如果速度是至关重要的,你可能会考虑其他的选择。

2

你是对的。你必须跟踪你的列的位置。也许在一个单独的结构中,或作为派生自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; 
    // ... 

end;

1

不管怎么说,对于那些(像我)谁到达了该网页寻找一种方式重新排序网格列:

type 
    THackAccess = class(TCustomGrid); 

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

输入列是从零开始的。