views:

522

answers:

2

I need to dynamically change position of certain column in DBGRid. Let's say I need to place column number 21 on position 10. I use:

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

But, this also changes the array itself, that means, that next time I want to access this column, I will need to write DBGrid.Columns[10], this makes it a little unclean, I need to memorize positions of all columns etc. Is there an easier way to reposition a column? It would also be good if array indexes do not change during this position change.

+1  A: 

You are right. You have to keep track of where your columns are located. Maybe in a separate structure, or as a descendant object derived from TCustomGrid.

I keep a container object, where I store, among other things, the size of the columns, the type of the data they contain, the sort order, formatting options, and the position in the grid. And then I have a custom grid that references the container.

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;

PA
+4  A: 

A simple way to deal with the problem is to not access the columns by index but by fieldname. Introduce a method like this:

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;

The drawback is that you have to run the loop every time you need to access the grid, causing a small delay, so if speed is essential you might consider other options.

Svein Bringsli