2004. november 2., kedd
How to programmatically change the column positions in a TDBGrid at runtime
Problem/Question/Abstract:
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.
Answer:
Solve 1:
type
TGridAccess = class(TCustomGrid);
{ Is needed because TCustomGrid.MoveColumn is protected. Declare it in the
imlementation section of the unit. }
procedure TForm1.Button1Click(Sender: TObject);
var
sField: string;
i: integer;
begin
sField := listbox1.Items[listbox1.itemindex];
with TGridAccess(DBGrid1) do
begin
for i := FixedCols to Columns.Count - 1 do
if Columns[i].Title.Caption = sField then
MoveColumn(Columns[i].Index + FixedCols, FixedCols);
end;
end;
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);
var
tempColumn: TColumn;
columnFound: Bool;
counter: Integer;
begin
columnFound := false;
{find the field's index number}
for counter := 0 to (dbGridView.Columns.Count - 1) do
begin
tempColumn := dbGridView.Columns[counter];
if tempColumn.FieldName = fieldName then
begin
columnFound := true;
break;
end;
end;
if columnFound then
tempColumn.Index := 0;
end;
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése