procedure TForm13.FormCreate(Sender: TObject); begin DBGrid1.Columns[0].Width:=180; end;
Delphi实现DBGrid列宽度自动调整https://www.cnblogs.com/tecsoon/archive/2009/03/04/1403037.html
procedure TForm13.FormCreate(Sender: TObject); begin DBGrid1.Columns[0].Field.Tag := 1 + Canvas.TextWidth(DBGrid1.Columns[0].Field.DisplayName); DBGrid1.Columns[1].Field.Tag := 1 + Canvas.TextWidth(DBGrid1.Columns[1].Field.DisplayName); DBGrid1.Columns[2].Field.Tag := 1 + Canvas.TextWidth(DBGrid1.Columns[2].Field.DisplayName); end;
Procedure FixDBGridColumnsWidth(const DBGrid: TDBGrid); var i: integer; TotWidth: integer; // 定义整个宽度 VarWidth: integer; // 定义变化的宽度 ResizableColumnCount: integer; // 定义变化宽度列的总数 AColumn: TColumn; begin // 在重新调整前所有列的宽度 TotWidth := 0; VarWidth := 0; // 有多少列需要自动调整 ResizableColumnCount := 0; for i := 0 to -1 + DBGrid.Columns.Count do begin TotWidth := TotWidth + DBGrid.Columns[i].Width; if DBGrid.Columns[i].Field.Tag <> 0 then Inc(ResizableColumnCount); end; // 为每个列分隔线增加1PX if dgColLines in DBGrid.Options then TotWidth := TotWidth + DBGrid.Columns.Count; if dgIndicator in DBGrid.Options then TotWidth := TotWidth + IndicatorWidth; VarWidth := DBGrid.ClientWidth - TotWidth; // 平均分配变化宽度的值 // 给所有需要自动调整的列 if ResizableColumnCount > 0 then VarWidth := VarWidth div ResizableColumnCount; for i := 0 to -1 + DBGrid.Columns.Count do begin AColumn := DBGrid.Columns[i]; if AColumn.Field.Tag <> 0 then begin AColumn.Width := AColumn.Width + VarWidth; if AColumn.Width < AColumn.Field.Tag then AColumn.Width := AColumn.Field.Tag; end; end; end;