自动调整最合适的DBGrid的宽度
(*
--- english -------------------------------------------------------------------
This will change (reduce or extend) the width of column(s) so they all
fit in the Grid.
If aChangeAll = False then only the last col will be modified.
--- german --------------------------------------------------------------------
Anpassung (Vergr ßerung oder Verkleinerung) der Spaltenbreite(n).
Wenn aChangeAll = False, dann wird nur die letzte Spalte ver ändert.
*)
procedure ChangeColumnWidths(DBGrid: TDBGrid; aChangeAll: boolean);
var
NewWidth,
TotalColumnWidth,
ColumnCount,
GridClientWidth,
StepWidth,
i: integer;
begin
ColumnCount := DBGrid.Columns.Count;
if ColumnCount = 0 then Exit;
// Ermitteln der momentanen Breite des Grids
// look for the actual size of all columns
TotalColumnWidth := 0;
for i := 0 to ColumnCount-1 do
TotalColumnWidth := TotalColumnWidth + DBGrid.Columns[i].Width;
if dgColLines in DBGrid.Options then
TotalColumnWidth := TotalColumnWidth + ColumnCount;
// Ermitteln der max. Breite des Grids
// What's the total Grid width?
GridClientWidth := DBGrid.Width - GetSystemMetrics(SM_CXVSCROLL);
if dgIndicator in DBGrid.Options then begin
GridClientWidth := GridClientWidth - IndicatorWidth;
if dgColLines in DBGrid.Options then
Dec(GridClientWidth);
end;
if DBGrid.BorderStyle = bsSingle then begin
if DBGrid.Ctl3D then // 2 * 2 Pixel
GridClientWidth := GridClientWidth - 4
else // 2 * 1 Pixel
GridClientWidth := GridClientWidth - 2;
end;
// Neue Spaltenbreiten setzen: vergößern
// change the width(s): extend size/width
if TotalColumnWidth < GridClientWidth then begin
StepWidth := (GridClientWidth - TotalColumnWidth) div ColumnCount;
// Alle Spalten anpassen
// for all columns
if aChangeAll then begin
for i := 0 to ColumnCount-1 do
DBGrid.Columns[i].Width := DBGrid.Columns[i].Width + StepWidth;
// Nur letzte Splate anpassen
// only for the last one
end else
DBGrid.Columns[ColumnCount-1].Width := DBGrid.Columns[ColumnCount-1].Width + ColumnCount * StepWidth;
end
// Neue Spaltenbreiten setzen: verkleinern
// change the width(s): reduce size/width
else if TotalColumnWidth > GridClientWidth then begin
StepWidth := (TotalColumnWidth - GridClientWidth) div ColumnCount;
if (TotalColumnWidth - GridClientWidth) mod ColumnCount <> 0 then Inc(StepWidth);
// Alle Spalten anpassen
// for all columns
if aChangeAll then begin
for i := 0 to ColumnCount-1 do begin
NewWidth := DBGrid.Columns[i].Width - StepWidth;
if (NewWidth > 5) then DBGrid.Columns[i].Width := NewWidth;
end;
// Nur letzte Splate anpassen
// only for the last one
end else begin
NewWidth := DBGrid.Columns[ColumnCount-1].Width - ColumnCount * StepWidth;
if (NewWidth > 5) then DBGrid.Columns[ColumnCount-1].Width := NewWidth;
end;
end;
end;