dbgrideh 单元格超出的文本用省略号替换

//这个问题困扰了我很久了,网上搜索了很长时间,下面这段代码只能在没有设置字段的情况下使用。
//若设置了字段,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;

转载于:https://www.cnblogs.com/piaoliuxia/archive/2008/11/12/1937283.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值