首页 > 开发 > 综合 > 正文

[DataGird]如何截取过长的字符串

2024-07-21 02:29:34
字体:
来源:转载
供稿:网友

  1.这段代码是处理过长字符串的主体;

void itemdatabound(object sender, datagriditemeventargs e)
{
   // get the string to be displayed
   string title = getthestring();

   // returns the updated text for the specified column
   string newtext = adjusttextfordisplay(title, 1, grid);
 
   // set the text including the tooltip when necessary
   e.item.cells[1].text = newtext;
}

  2.adjusttextfordisplay(string,int,datagrid)函数的功能是根据列的宽度,截取过长的字符串;这里需要注意的是datagrid的font和columns[colindex].itemstyle.width属性必需有赋值。如果没有赋值的话,函数将会采用系统默认的值。如不加处理,函数会出异常。

string adjusttextfordisplay(string text, int colindex, datagrid grid)
{
   // calculate the dimensions of the text with the current font
   sizef textsize = measurestring(text, grid.font);
 
   // compare the size with the column's width
   int colwidth = (int) grid.columns[colindex].itemstyle.width.value;
   if(textsize.width > colwidth)
   {
      // get the exceeding pixels
      int delta = (int) (textsize.width - colwidth);
 
      // calculate the average width of the characters (approx)
      int avgcharwidth = (int) (textsize.width/text.length);
 
      // calculate the number of chars to trim to stay in the fixed width (approx)
      int chrtotrim = (int) (delta/avgcharwidth);
 
      // get the proper substring + the ellipsis
      // trim 2 more chars (approx) to make room for the ellipsis
      string rawtext = text.substring(0, text.length-(chrtotrim+2)) + "";
 
      // format to add a tooltip
      string fmt = "{1}";
      return string.format(fmt, text, rawtext);
   }
   return text;
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表