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;
}
新聞熱點
疑難解答