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.
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.