function GetColMaxDataLength(ASGrid: TStringGrid; ACol, AStartRow: Integer): Integer;
//三個(gè)自定義函數(shù)和過程放在implementation 后面
//----------------------------------------------------------------------------//
//取得某一列數(shù)據(jù)的最大長(zhǎng)度
//----------------------------------------------------------------------------//
var
ColIndex, RowIndex: Integer;
MaxColLength: Integer; //列數(shù)據(jù)的最大長(zhǎng)度
begin
MaxColLength := 0;
with ASGrid do
begin
//取得列數(shù)據(jù)的最大長(zhǎng)度
for RowIndex := AStartRow to RowCount - 1 do
begin
if length(Cells[ACol, RowIndex]) > MaxColLength then
begin
MaxColLength:= length(Cells[ACol, RowIndex]);
end;
end;
end;
result := MaxColLength;
end;
//----------------------------------------------------------------------------//
//根據(jù)數(shù)據(jù)長(zhǎng)度自動(dòng)設(shè)置指定列的列寬
//----------------------------------------------------------------------------//
procedure SetOneColWidth(ASGrid: TStringGrid; ACol: Integer);
var
OneCharPixel: Integer; //一個(gè)字符所占的像素?cái)?shù)
RightSpaceWidth: Integer; //右邊距空隙
begin
RightSpaceWidth := 3; //設(shè)置為3達(dá)到和左邊距一致的效果
OneCharPixel := 6; //6對(duì)應(yīng)9號(hào)字[*此處最好寫成一個(gè)根據(jù)字號(hào)獲得像素值的函數(shù)*]
ASGrid.ColWidths[ACol] := GetColMaxDataLength(ASGrid, ACol, 0) * OneCharPixel
+ RightSpaceWidth;
end;
//----------------------------------------------------------------------------//
//根據(jù)數(shù)據(jù)長(zhǎng)度自動(dòng)設(shè)置全部列的列寬
//----------------------------------------------------------------------------//
procedure SetAllColWidth(ASGrid: TStringGrid);
var
ColIndex: Integer; //需要設(shè)置的列
begin
for ColIndex := 0 to ASGrid.ColCount - 1 do
begin
SetOneColWidth(ASGrid, ColIndex);
end;
end;
procedure TForm1.BitBtn10Click(Sender: TObject);
var i:Integer;
begin //stringgrid設(shè)置單獨(dú)列自動(dòng)列寬
i:=StrToInt(Trim(Edit1.Text));
//ShowMessage(IntToStr(GetColMaxDataLength(StringGrid1,i,0))); //調(diào)用implementation下面定義的函數(shù)
SetOneColWidth(StringGrid1,i)
end;
procedure TForm1.BitBtn11Click(Sender: TObject);
begin //stringgrid全部自動(dòng)列寬
SetAllColWidth(StringGrid1);
end;
------------------------------------------------------------
procedure TForm1.BitBtn10Click(Sender: TObject);
var i:Integer;
begin //stringgrid設(shè)置單獨(dú)列自動(dòng)列寬
i:=StrToInt(Trim(Edit1.Text));
//ShowMessage(IntToStr(GetColMaxDataLength(StringGrid1,i,0))); //調(diào)用implementation下面定義的函數(shù)
SetOneColWidth(StringGrid1,i)
end;
procedure TForm1.BitBtn11Click(Sender: TObject);
begin //stringgrid全部自動(dòng)列寬
SetAllColWidth(StringGrid1);
end;
end.
聯(lián)系客服