一直在找最好的根据DBGridEH(或者DBGrid)的内容和标题栏设置自适应列宽的方法,一直没有太好的。今天从园地上发现了源码:地址如下,非常好用。与大家分享:
http://www.delphifans.com/SoftView/SoftView_2019.html
代码哪下:
//需要定义这个类,才能使用OptimizeSelectedColsWidth方法调整列宽
type
TZYDBGridEH = class(TCustomDBGridEh)
public
end;
我在原来的基础上进行修改的实现代码:
//表格内容和字段标题宽度设置列宽
procedure SetDBGridColumnsWidth(Grid: TCustomDBGridEh);
var
i: integer;
begin
if not Assigned(Grid.DataSource) then Exit;
if not Grid.DataSource.Dataset.Active then Exit;
try
Grid.DataSource.Dataset.DisableControls;
for i := 0 to TDBGridEh(Grid).Columns.Count - 1 do
begin
TZYDBGridEh(Grid).OptimizeSelectedColsWidth(TDBGridEh(Grid).Columns[i]);
end;
Grid.DataSource.Dataset.EnableControls;
except on E: Exception do
begin
Error('设置表格' + Grid.Name + '出错!' + E.Message);
end;
end;
end;
另外,还有根据列的所有行内容进行设置,当数据量大时,速度就会很慢,还有就是有时候设置会出错(有用同样的办法设置窗体中的多个DBGridEH,就有一个总是出错)。但也贴出来,供大家参考:
procedure SetDBGridColumnsWidth(DBGridName:TDBGridEH);
var
j, maxWidth: integer;
begin
if not Assigned(DBGridName.DataSource) then Exit;
if not DBGridName.DataSource.Dataset.Active then Exit;
try
DBGridName.DataSource.Dataset.DisableControls;
for j := 0 to DBGridName.Columns.Count - 1 do
begin
DBGridName.DataSource.Dataset.First;
maxWidth := DBGridName.Canvas.TextWidth(Trim(DBGridName.Columns[j].Title.Caption));
while not DBGridName.DataSource.Dataset.Eof do
begin
if maxWidth < DBGridName.Canvas.TextWidth(Trim(DBGridName.DataSource.Dataset.FieldByName(DBGridName.Columns[j].FieldName).AsString)) then
maxWidth := DBGridName.Canvas.TextWidth(Trim(DBGridName.DataSource.Dataset.FieldByName(DBGridName.Columns[j].FieldName).AsString))
else
DBGridName.DataSource.Dataset.Next;
end;
DBGridName.Columns[j].Width := maxWidth + 20;
end;
DBGridName.DataSource.DataSet.First;
DBGridName.DataSource.Dataset.EnableControls;
except
Error('设置表格' + DBGridName.Name + '出错!');
end;
end;
另外,设置DBGrid的方法,用上面的方法就一不太好用了。网上的方法(来自大富翁论坛)如下:
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
nWidth: Integer;
begin
with DBGrid1.Canvas do begin
nWidth := TextWidth(Column.Field.AsString) + 2;
if nWidth > Column.Width then Column.Width := nWidth;
end;
end;