电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

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


发布日期:2021/9/11
 

这段代码是处理过长字符串的主体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}

上一篇:用户控件包装器的设计与实现

下一篇:编程高手 DotNet异步消息处理方法