首页  编辑  

数据网格自动适应宽度

Tags: /超级猛料/Friends.网友专栏/zswang/函数大全/   Date Created:
(*//
标题:数据网格自动适应宽度
说明:使用DBGrid不可不看
设计:Zswang
日期:2002-03-04
支持:wjhu111@21cn.com
//*)
/// ////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.Button1Click(Sender: TObject);
begin
    DBGridAutoSize(DBGrid1);
end;
/// ////End Demo