We have been looking for the best method to set an adaptive column width based on the content and title bar of dbgrideh (or DBGrid). It has never been very good. Today, we found the source code from the garden: The address is as follows, which is very useful. Share with you:
Http://www.delphifans.com/SoftView/SoftView_2019.html
CodeUnder:
// You need to define this class before using the optimizeselectedcolswidth method to adjust the column width
Type
Tzydbgrideh = Class (tcustomdbgrideh)
Public
End;
The implementation code I modified on the basis of the original one:
// Set the column width for table content and field title width
Procedure setdbgridcolumnswidth (Grid: tcustomdbgrideh );
VaR
I: integer;
Begin
If not assigned (grid. datasource) Then exit;
If not grid. datasource. dataset. Active then exit;
Try
Grid. datasource. dataset. disablecontrols;
For I: = 0 to tdbgrideh (GRID). Columns. Count-1 do
Begin
Tzydbgrideh (GRID). optimizeselectedcolswidth (tdbgrideh (GRID). Columns [I]);
End;
Grid. datasource. dataset. enablecontrols;
Except t on E: exception do
Begin
Error ('settings table' + grid. Name + 'error! '+ E. Message );
End;
End;
End;
In addition, you can also set it based on the content of all rows in the column. When the data volume is large, the speed will be very slow, and sometimes the setting will fail (using the same method to set multiple dbgrideh in the form, there is always an error ). But it is also posted for your reference:
Procedure setdbgridcolumnswidth (dbgridname: tdbgrideh );
VaR
J, maxwidth: integer;
Begin
If not assigned (dbgridname. datasource) Then exit;
If not dbgridname. datasource. dataset. Active then exit;
Try
Dbgridname. datasource. dataset. disablecontrols;
For J: = 0 to dbgridname. Columns. Count-1 do
Begin
Dbgridname. datasource. dataset. first;
Maxwidth: = dbgridname. Canvas. textwidth (TRIM (dbgridname. Columns [J]. Title. Caption ));
While not dbgridname. datasource. dataset. EOF do
Begin
If maxwidth <dbgridname. Canvas. textwidth (TRIM (dbgridname. datasource. dataset. fieldbyname (dbgridname. Columns [J]. fieldname). asstring) then
Maxwidth: = dbgridname. Canvas. textwidth (TRIM (dbgridname. datasource. dataset. fieldbyname (dbgridname. Columns [J]. fieldname). asstring ))
Else
Dbgridname. datasource. dataset. Next;
End;
Dbgridname. Columns [J]. Width: = maxwidth + 20;
End;
Dbgridname. datasource. dataset. first;
Dbgridname. datasource. dataset. enablecontrols;
Except
Error ('settings table' + dbgridname. Name + 'error! ');
End;
End;
In addition, the method for setting DBGrid is not easy to use. The method on the Internet (from the monopoly Forum) is as follows:
Procedure tform1.dbgrid1drawcolumncell (Sender: tobject; const rect: trect;
Datacol: integer; column: tcolumn; State: tgriddrawstate );
VaR
Nwidth: integer;
Begin
With dbgrid1.canvas do begin
Nwidth: = textwidth (column. Field. asstring) + 2;
If nwidth> column. Width then column. Width: = nwidth;
End;
End;