DBGridEh列宽自动适应内容的简单方法
///////Begin Source
uses
Math;
function
DBGridRecordSize(mColumn: TColumn):
Boolean
;
{ 返回记录数据网格列显示最大宽度是否成功 }
begin
Result :=
False
;
if
not
Assigned(mColumn
.
Field)
then
Exit;
mColumn
.
Field
.
Tag := Max(mColumn
.
Field
.
Tag,
TDBGrid(mColumn
.
Grid).Canvas
.
TextWidth(mColumn
.
Field
.
DisplayText));
Result :=
True
;
end
;
{ DBGridRecordSize }
function
DBGridAutoSize(mDBGrid: TDBGrid; mOffset:
Integer
=
5
):
Boolean
;
{ 返回数据网格自动适应宽度是否成功 }
var
I:
Integer
;
begin
Result :=
False
;
if
not
Assigned(mDBGrid)
then
Exit;
if
not
Assigned(mDBGrid
.
DataSource)
then
Exit;
if
not
Assigned(mDBGrid
.
DataSource
.
DataSet)
then
Exit;
if
not
mDBGrid
.
DataSource
.
DataSet
.
Active
then
Exit;
for
I :=
0
to
mDBGrid
.
Columns
.
Count -
1
do
begin
if
not
mDBGrid
.
Columns[I].Visible
then
Continue;
if
Assigned(mDBGrid
.
Columns[I].Field)
then
mDBGrid
.
Columns[I].Width := Max(mDBGrid
.
Columns[I].Field
.
Tag,
mDBGrid
.
Canvas
.
TextWidth(mDBGrid
.
Columns[I].Title
.
Caption)) + mOffset
else
mDBGrid
.
Columns[I].Width :=
mDBGrid
.
Canvas
.
TextWidth(mDBGrid
.
Columns[I].Title
.
Caption) + mOffset;
mDBGrid
.
Refresh;
end
;
Result :=
True
;
end
;
{ DBGridAutoSize }
///////End Source
///////Begin Demo
procedure
TForm1
.
DBGrid1DrawColumnCell(Sender: TObject;
const
Rect: TRect;
DataCol:
Integer
; Column: TColumn; State: TGridDrawState);
begin
DBGridRecordSize(Column);
end
;
procedure
TForm1
.
Button2Click(Sender: TObject);
begin
DBGridAutoSize(DBGrid1);
end
;
///////End Demo
procedure TFm_ReadExcel.FormCreate(Sender: TObject);
begin
inherited;
dbgrideh1.RowHeight:=15;
end;
上述代表需要执行两次OPEN,才能看到效果