How to programmatically change the column positions in a TDBGrid at runtime (Views: 100)


When a user selects some items (Field Names) from a TListBox, I need a TDBGrid to rearrange those columns so that they are shown first, i.e. the left hand side of the grid. You can do this at runtime by dragging the columns where you want them and then saving that grid configuration in a file to be reopened next time. I need to do it as soon as the user selects say 'Jan,Feb,Mar'... These fields are normally in the middle of the grid. I've looked at a lot of the properties of the grid and columns but can't figure it out.


Solve 1:

  TGridAccess = class(TCustomGrid);
  { Is needed because TCustomGrid.MoveColumn is protected. Declare it in the
  imlementation section of the unit. }

procedure TForm1.Button1Click(Sender: TObject);
  sField: string;
  i: integer;
  sField := listbox1.Items[listbox1.itemindex];
  with TGridAccess(DBGrid1) do
    for i := FixedCols to Columns.Count - 1 do
      if Columns[i].Title.Caption = sField then
        MoveColumn(Columns[i].Index + FixedCols, FixedCols);

Solve 2:

When you change indexes on a table, you might want to pull the column that the table is sorted by to the 1st column position. Here's how to move a column to the 1st column position in a normal TDBGrid:

procedure TForm1.MoveColumnToFront(fieldName: string);
  tempColumn: TColumn;
  columnFound: Bool;
  counter: Integer;
  columnFound := false;
  {find the field's index number}
  for counter := 0 to (dbGridView.Columns.Count - 1) do
    tempColumn := dbGridView.Columns[counter];
    if tempColumn.FieldName = fieldName then
      columnFound := true;
  if columnFound then
    tempColumn.Index := 0;

<< Back to main page