Delphi實現DBGrid列寬度自動調整

來源:互聯網
上載者:User

  在本文中我將提供一個簡便的過程(Procedure)來解決上面的問題,它能夠在程式運行時自動固定TDBGrid中所顯示列的寬度。

  首先,在TForm的OnCreate事件中添加下面的代碼:

  Procedure TForm1.FormCreate(Sender: TObject);
  begin

  //在Tag屬性中設定需要自動調整的列的最小寬度(固定值)

  //這裡將列寬值設為40px

  Table1.FieldByName('FirstName').Tag := 40;

  //這裡設定一個變化的值

  //該值是做過運算的欄位標題的寬度值

  Table1.FieldByName('LastName').Tag := 4 + Canvas.TextWidth( Table1.FieldByName('LastName').DisplayName);
  end;

  其次,最關鍵的一個過程(Procedure),就是用它來控制列的寬度:

  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;

  最後,應用這一個函數:

  Procedure TForm1.FormResize(Sender: TObject);
  begin
  FixDBGridColumnsWidth(DBGrid1);
  end;

  上面一個簡單的函數解決了經常會碰到的關於資料列的問題,遇到問題時多多開動腦筋,而不要一味的去找第三方控制項,這樣長期堅持下去就會真正提高自己的水平,才會從一名程式泥水匠變成真正的軟體設計師。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.