熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

[DataGird]如何截取過長的字符串

2022-06-13   來源: .NET編程 

  這段代碼是處理過長字符串的主體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}


From:http://tw.wingwit.com/Article/program/net/201311/12632.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.