String
1. This code is the main body that handles too long strings;
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;
}
The function of the 2.AdjustTextForDisplay (String,int,datagrid) function is to intercept a string that is too long based on the width of the column; the font and columns[colindex of the DataGrid should be noted here. The Itemstyle.width property must be assigned a value. If no value is assigned, the function will take the system default value. If you do not add, the function will be an exception.
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;
}