Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8850555
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T12:55:50+00:00 2026-06-14T12:55:50+00:00

Continuing with the project started in: How to auto fit/scale DBGrid's (or other similar)

  • 0

Continuing with the project started in:

How to auto fit/scale DBGrid's (or other similar) columns widths according to its contents?

I used the @alzaimar answer to auto fit the columns according to their content width, but he showed me how to increase the width, but not how to decrease, so I complemented the code as shown above:

procedure TRecordsBrowserFrameBase.JvDBGrid2DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  h, p, g, r, w, t : Integer;
const
  colSpc = 10;
begin
{ ajusta as colunas de uma grade de acordo com o conteúdo das células }
  h := Column.DropDownRows;
  p := (Sender as TJvDBGrid).CurrentDrawRow;
  g := Column.Width;
  r := (Sender as TJvDBGrid).VisibleRowCount;
  w := colSpc + (Sender as TJvDBGrid).Canvas.TextExtent(Column.Field.DisplayText).cx;
  t := colSpc + (Sender as TJvDBGrid).Canvas.TextExtent(Column.Title.Caption).cx;
{$WARNINGS OFF}
  // increase column width if needed
  if (w > g) then Column.Width := w;
  if (g < t) then Column.Width := t;
  if (p < r) and (h < w) then Column.DropDownRows := w;
  // decrease column size if needed (10th line)
  if (p = r) then
  begin
    h := Column.DropDownRows;
    g := Column.Width;
    if (h > t) and (h < g) then Column.Width := Column.DropDownRows;
    Column.DropDownRows := 0;
  end;
{$WARNINGS ON}
end;

So, now when I scroll with the down arrow key, the selected row color does not always is in the correct position as you can see in this picture:

enter image description here

What I am doing wrong?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T12:55:51+00:00Added an answer on June 14, 2026 at 12:55 pm

    This solution makes all columns expand or shrink according to it’s contents, without care if there has to be scroll bars or not, and fix the selected cell drawing malfunction and the the record pointer malfunction.

    type
      TColumnAutoAdjust = record {Save the information responsible for setting column widths in the grid}
        Field: String;           {Field name whose information is being stored}
        Registered: Boolean;     {Indicates whether the size of this column already registered}
        Updated: Boolean;        {Indicates the actual size of the column was updated}
        LastWidth: Integer;      {Width indicates the final text of a record of a row column}
        CurrWidth: Integer;      {Indicates the current size and column width}
        Reverter: Integer;       {Indicates the greatest width recorded but that is less than the current}
        Scrolls: Integer;        {Indicates the amount of scrolls present after one width adjustment}
        RecNo: Integer;          {Indicates which was the record in the table which increased the width of colune}
      end;
    
    var { inside the forms private }
      gdCols: array of TColumnAutoAdjust; { vetor de ajuste de largura de cada coluna na grade de resultado }
      RegisteredCols: Integer; { quantas colunas já foram registradas no controle de ajuste }
      gdVisibleRows: Integer; { quantas linhas de cadastros estão visíveis da grade de resultado }
      gdVisibleCols: Integer; { quantas colunas de cadastros estão visíveis da grade de resultado }
    
    { before showing the grid }  
        RegisteredCols := ResultGrid.Columns.Count;
        SetLength(gdCols, RegisteredCols); { determina o tamanho da vetor de controle de colunas }
        { libera a lista }
        ResultGrid.Align := alClient;
        for i := 0 to RegisteredCols -1 do { inicializando a largura das colunas no tamanho do título de cada }
        begin
          gdCols[i].Field := ResultGrid.Columns[i].FieldName;
          ResultGrid.Columns[i].Width := ResultGrid.Canvas.TextExtent(ResultGrid.Columns[i].Title.Caption).cx;
          ResultGrid.Columns[i].Alignment := taLeftJustify;
          ResultGrid.Columns[i].Title.Alignment := taLeftJustify;
        end;
        BrowserQuery.Open;
        ResultGrid.Show;
        for i := 0 to gdVisibleRows do
        begin
          BrowserQuery.Next;
          ResultGrid.Refresh;
        end;
        for i := 0 to gdVisibleRows do
        begin
          BrowserQuery.Prior;
          ResultGrid.Refresh;
        end;
        BrowserQuery.First;
        ResultGrid.SetFocus;
      end
    
    { after dataset scroll}      
    procedure TRecordsBrowserFrameBase.BrowserQueryAfterScroll(DataSet: TDataSet);
    var
      i, TitleWidth: Integer;
      mayAdjustAgain: Boolean; {  }
    begin
    { ajusta as colunas da grade de resultado a cada movimento da tabela de resultado }
      mayAdjustAgain := False;
      for i := 0 to RegisteredCols -1 do
      begin
        if not gdCols[i].Updated then
        begin
          ResultGrid.Columns[i].Width := gdCols[i].CurrWidth;
          gdCols[i].Scrolls := 0;
          gdCols[i].Updated := True;
        end
        else
        begin
          Inc(gdCols[i].Scrolls);
          if (DataSet.RecNo > gdCols[i].RecNo + gdVisibleRows) or (DataSet.RecNo < gdCols[i].RecNo - gdVisibleRows) then
          begin
            TitleWidth := MaxColSpacing + ResultGrid.Canvas.TextExtent(ResultGrid.Columns[i].Title.Caption).cx;
            gdCols[i].LastWidth := gdCols[i].CurrWidth;
            gdCols[i].CurrWidth := IFX(gdCols[i].Reverter > TitleWidth, gdCols[i].Reverter, TitleWidth);
            gdCols[i].Reverter := IFX(gdCols[i].Reverter > TitleWidth, TitleWidth, 0);
            gdCols[i].Updated := False;
            mayAdjustAgain := True;
          end;
        end;
      end;
      if mayAdjustAgain then
      begin
        ResultGrid.Refresh;
        BrowserQueryAfterScroll(DataSet);
      end;
    end;
    
    { on draw column cell }
    
    procedure TRecordsBrowserFrameBase.GridColumnWidthAdjust(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
    var
      ColWidth, TextWidth, TitleWidth: Integer;
    begin
    { ajusta a capitalização do texto das células }
      (Sender as TJvDBGrid).Canvas.Pen.Color := clWhite;
      (Sender as TJvDBGrid).Canvas.Rectangle(Rect);
      (Sender as TJvDBGrid).Canvas.TextOut(Rect.Left+2, Rect.Top+2, NameCase(Column.Field.DisplayText));
    { ajusta as colunas de uma grade de acordo com o conteúdo das células }
      gdVisibleRows := (Sender as TJvDBGrid).VisibleRowCount;
      gdVisibleCols := (Sender as TJvDBGrid).VisibleColCount;
      TitleWidth := MaxColSpacing + (Sender as TJvDBGrid).Canvas.TextExtent(Column.Title.Caption).cx;
      TextWidth := MaxColSpacing + (Sender as TJvDBGrid).Canvas.TextExtent(NameCase(Column.Field.DisplayText)).cx;
      ColWidth := Column.Width;
      {$WARNINGS OFF}
      if (TextWidth > gdCols[DataCol].Reverter) and (TextWidth < ColWidth) then gdCols[DataCol].Reverter := TextWidth;
      if (TextWidth > ColWidth) then { texto da célula é mais largo que a coluna }
      begin
        gdCols[DataCol].Registered := True;
        gdCols[DataCol].LastWidth := ColWidth;
        gdCols[DataCol].CurrWidth := TextWidth;
        gdCols[DataCol].Updated := False;
        gdCols[DataCol].RecNo := BrowserQuery.RecNo;
        gdCols[DataCol].Reverter := TitleWidth;
        Exit;
      end;
      if (ColWidth < TitleWidth) then { texto da célula é menor que o título da coluna }
      begin
        gdCols[DataCol].Registered := True;
        gdCols[DataCol].LastWidth := ColWidth;
        gdCols[DataCol].CurrWidth := TitleWidth;
        gdCols[DataCol].Updated := False;
        gdCols[DataCol].Reverter := TitleWidth;
        Exit;
      end;
    {$WARNINGS ON}
    end;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Continuing with the project started in: How to auto fit/scale DBGrid's (or other similar)
In an iOS Project with folders containing *.m files, similar to packages, one will
I recently started using Mac OS X for a flex/actionscript project and having a
I have started to use git for my projects, when I create a project
I started this project a long long time ago when I was just beginning
Sorry about the confusing title. I recently started doing this in my project, and
I've started a simple project in which it must get an image containing text
I'm getting started on a new MVC project where there are some peculiar rules
We've recently started a small-ish project for a mobile site demo w/.NET4; jquery-mobile has
As of late, we started a pretty large project (C# XNA game). It seemed

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.