DELPHI基础:DELPHI数据网格自动适应宽度计算机二级考试
文章作者 100test 发表时间 2009:04:09 22:57:48
来源 100Test.Com百考试题网
DELPHI数据网格自动适用宽度是经常要用的代码,这个代码很经典,很有用,最好最近学会自己写。
//////源代码如下:
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 }
///////源代码结束
///////使用示例开始
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject. const Rect: TRect.
DataCol: Integer. Column: TColumn. State: TGridDrawState).
begin
DBGridRecordSize(Column).
end.
procedure TForm1.Button1Click(Sender: TObject).
begin
DBGridAutoSize(DBGrid1).
end.
///////使用示例结束