function GetColMaxDataLength(ASGrid: TStringGrid; ACol, AStartRow: Integer): Integer; //三个自定义函数和过程放在implementation 后面 //----------------------------------------------------------------------------// //取得某一列数据的最大长度 //----------------------------------------------------------------------------// var ColIndex, RowIndex: Integer; MaxColLength: Integer; //列数据的最大长度 begin MaxColLength := 0; with ASGrid do begin //取得列数据的最大长度 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; //----------------------------------------------------------------------------// //根据数据长度自动设置指定列的列宽 //----------------------------------------------------------------------------// procedure SetOneColWidth(ASGrid: TStringGrid; ACol: Integer); var OneCharPixel: Integer; //一个字符所占的像素数 RightSpaceWidth: Integer; //右边距空隙 begin RightSpaceWidth := 3; //设置为3达到和左边距一致的效果 OneCharPixel := 6; //6对应9号字[*此处最好写成一个根据字号获得像素值的函数*] ASGrid.ColWidths[ACol] := GetColMaxDataLength(ASGrid, ACol, 0) * OneCharPixel + RightSpaceWidth; end;
//----------------------------------------------------------------------------// //根据数据长度自动设置全部列的列宽 //----------------------------------------------------------------------------// procedure SetAllColWidth(ASGrid: TStringGrid); var ColIndex: Integer; //需要设置的列 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设置单独列自动列宽 i:=StrToInt(Trim(Edit1.Text)); //ShowMessage(IntToStr(GetColMaxDataLength(StringGrid1,i,0))); //调用implementation下面定义的函数 SetOneColWidth(StringGrid1,i) end;
procedure TForm1.BitBtn11Click(Sender: TObject); begin //stringgrid全部自动列宽 SetAllColWidth(StringGrid1); end;
------------------------------------------------------------
procedure TForm1.BitBtn10Click(Sender: TObject); var i:Integer; begin //stringgrid设置单独列自动列宽 i:=StrToInt(Trim(Edit1.Text)); //ShowMessage(IntToStr(GetColMaxDataLength(StringGrid1,i,0))); //调用implementation下面定义的函数 SetOneColWidth(StringGrid1,i) end;
procedure TForm1.BitBtn11Click(Sender: TObject); begin //stringgrid全部自动列宽 SetAllColWidth(StringGrid1); end;
end.
|