在GridView列中拟合长文本

我在ASP.NET gridview列中显示长文本时遇到问题。 我不希望文本换行到第二行,因为它是业务要求不包装的。

理想情况下,我想要某种基于服务器或客户端的代码,它可以帮助我将文本截断为列的大小,然后可能会显示更多按钮或“…”以获取更多文本?

当点击更多按钮或…时; 弹出窗口显示文本的其余部分或全文。

注意:文本或字符串大小各不相同,可以是25到75个字符之间的任意长度。

关于如何实现上述目标的任何想法? 谢谢

将此CSS类用于gridview列

 .ellipsis { white-space: nowrap; text-overflow: ellipsis; width: 50px; display: block; overflow: hidden; } 

它将…放在列的末尾,具有特定的宽度。

更新

标记

                    

CSS

 .employees-grid { table-layout: fixed; width: 100%; } .employees-grid-id { width: 5%; } .employees-grid-first-name { width: 10%; } .employees-grid-last-name { width: 10%; } .employees-grid-email { width: 15%; } .employees-grid-note { width: 100%; white-space: nowrap; text-overflow: ellipsis; display: block; overflow: hidden; } 

如果您担心格式化,我会构建我的查询(您将GridView绑定到的查询),以便以两种forms返回数据。

 Select Left(dataColumn, 20) as TruncatedData, dataColumn as FullData From table 

然后,您可以将GridView绑定到TruncatedData列,并将工具提示绑定到FullData列,这样当它们hover时,它们将获得完整的列数据。 我将BoundField转换为TemplateField并填充它:

       

您应该发布您尝试过的代码,以便人们可以提出更改/改进等等。无论如何,我必须编写一个代码,按照您要查找的内容进行操作,所以在这里您可以拥有它。

 private string[] truncateText(string iniText, int colNumber, int noAddRows) { string[] outStrings = new string[noAddRows + 3]; if (noAddRows == 0) { outStrings = new string[22]; } outStrings[1] = iniText; int addBit = 10; int maxLength = (int)GridView1.Columns[colNumber].ItemStyle.Width.Value + addBit; int linesCount = 1; if (iniText.Length > maxLength) { outStrings[1] = iniText.Substring(0, maxLength); //New truncated string outStrings[2] = iniText.Substring(maxLength, iniText.Length - maxLength); //Remaining bit linesCount = 2; if (noAddRows > -1 && outStrings[2].Length > maxLength) { //Further lines of the truncated bit string remBit = outStrings[2].Substring(maxLength, outStrings[2].Length - maxLength); outStrings[2] = outStrings[2].Substring(0, maxLength); while (remBit.Length > 0) { linesCount = linesCount + 1; if ((noAddRows > 0 && linesCount > noAddRows + 2) || linesCount > 20) { linesCount = linesCount - 1; if (remBit.Length > 0) { outStrings[linesCount] = outStrings[linesCount] + remBit; } break; } if (remBit.Length <= maxLength) { outStrings[linesCount] = remBit; break; } else { outStrings[linesCount] = remBit.Substring(0, maxLength); remBit = remBit.Substring(maxLength, remBit.Length - maxLength); } } } } outStrings[0] = Convert.ToString(linesCount); //Total number of lines return outStrings; } 

你可以这样称呼它:

 string[] truncatedLines = truncateText("text to truncate", colNo, noAdd); 

输出string[]保存截断的所有行,使它们适合给定列的宽度+一小部分(我设置为10的addBit )。 使用noAddRows参数可以控制所需的行数作为输出:如果将其设置为零,则根据给定的列宽度返回所需的行数。 数组的0位置保留为返回的总行数。

我想你不会发现任何问题,使用这段代码可以完全控制你想要实现的function。