//这个问题困扰了我很久了,网上搜索了很长时间,下面这段代码只能在没有设置字段的情况下使用。
//若设置了字段,drawdatacell就无法正常执行,可以改在DrawColumnCell事件中。
//另外就是这段代码不能正常处理全角字符或者汉字,会有乱码出现。 
procedure TForm1.DBGridEh1DrawDataCell(Sender: TObject; const Rect: TRect;
  Field: TField; State: TGridDrawState);
var
  str: string;
  i: Integer;
begin
  if DBGridEh1.Canvas.TextWidth(Field.AsString) > (Rect.Right - Rect.Left - 4) then
  begin
    i := 1;
    while DBGridEh1.Canvas.TextWidth(str) < (Rect.Right - Rect.Left - DBGridEh1.Canvas.TextWidth('...') - 4) do
    begin
      str := str + Field.AsString[i];
      Inc(i);
      if i > Length(Field.AsString) then
        Break;
    end;
    DBGridEh1.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2,str + '...');
  end
  else
    DBGridEh1.DefaultDrawDataCell(Rect,Field,State);
end;

//改进后的代码如下:


procedure TForm1.DBGridEh1DrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumnEh;
  State: TGridDrawState);
var
  str,strTemp, strField: string;
  i, nWidth: Integer;
begin
  strField := Column.Field.AsString;
  if DBGridEh1.Canvas.TextWidth(strField) > (Rect.Right - Rect.Left - 4) then
  begin
    i := 1;
    nWidth := Rect.Right - Rect.Left - DBGridEh1.Canvas.TextWidth('...') - 4;
    while DBGridEh1.Canvas.TextWidth(str) < nWidth do
    begin
      if i > Length(strField) then
        Break;
      strTemp := strField[i];
      if (Ord(strField[i]) > 128) and (i < Length(strField)) then
      begin
        strTemp := strTemp + strField[i + 1];
      end;
      if DBGridEh1.Canvas.TextWidth(str + strTemp) <= nWidth then
      begin
        str := str + strTemp;
        i := i + Length(strTemp);
      end
      else
        Break;
    end;
    DBGridEh1.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2,str + '...');
  end
  else
    DBGridEh1.DefaultDrawColumnCell(Rect,DataCol,Column,State);
end;

posted on 2008-11-12 00:56  漂流侠  阅读(820)  评论(0编辑  收藏  举报