这段代码是处理过长字符串的主体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 grid) // Set the text including the tooltip when necessary eItemCells[]Text = newText} AdjustTextForDisplay(stringintDataGrid)函数的功能是根据列的宽度截取过长的字符串这里需要注意的是DataGrid的Font和Columns[colIndex]ItemStyleWidth属性必需有赋值如果没有赋值的话函数将会采用系统默认的值如不加处理函数会出异常 string AdjustTextForDisplay(string text int colIndex DataGrid grid) { // Calculate the dimensions of the text with the current font SizeF textSize = MeasureString(text gridFont) // Compare the size with the columns width int colWidth = (int) gridColumns[colIndex]ItemStyleWidthValueif(textSizeWidth > colWidth) { // Get the exceeding pixels int delta = (int) (textSizeWidth colWidth) // Calculate the average width of the characters (approx) int avgCharWidth = (int) (textSizeWidth/textLength) // 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 more chars (approx) to make room for the ellipsis string rawText = textSubstring( textLength(chrToTrim+)) + // Format to add a tooltip string fmt = {}return StringFormat(fmt text rawText)} return text} |