[Datagird] How to intercept a string that is too long

Source: Internet
Author: User
Tags format trim
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;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.