限制GridView列中的文本大小
我有一个asp:GridView声明如下:
<asp:LinkButton ID="DeleteButton" CommandArgument='' CommandName="Remove" runat="server">Remove
我的问题是100%美学。 为长描述而发生的自动换行使表格看起来很俗气。 我想用长描述做的是当描述太长时有一个省略号(…)
长描述等等等等……
我找不到内置的方法,所以我决定尝试实现GridView的这个OnRowDataBound
。
protected void Ds_my_projects_RowDataBound(object sender, GridViewRowEventArgs e) { DataRow curRow = ((DataRowView)e.Row.DataItem).Row; if (curRow["Description"].ToString().Length > 200) curRow["Description"] = curRow["Description"].ToString().Substring(0, 200) + "..."; }
我在第一行上遇到运行时exception,因为Object引用未设置为对象的实例 。
我在这做错了什么? 有没有更简单的方法来完成我想要做的事情?
您可以使用css并将其添加到Grid
css类来处理它:
.Grid { table-layout:fixed; width:100%; } .Grid .Shorter { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
更新 :我修改了上面的类,以便您可以通过使用ItemStyle-CssClass属性来影响单个列,如下所示:
我要做的是创建一个可以缩短字符串的Extension类。 静态类将具有类似以下方法:
public static string Shorten(this string name, int chars) { if (name.ToCharArray().Count() > chars) { return name.Substring(0, chars) + "..."; } else return name; }
然后,您可以将BoundFields用作TemplateFields,如下所示:
" />
关于这一点的Shorten()
是你现在可以在任何地方使用Shorten()
方法。
CAbbot有一个很好的建议。 我从来没有这样做,但如果这对你有用,那么我喜欢那样; 简洁,优雅,高效。
我一直这样做的方式是通过DataSource。 如果要将SqlDataSource
绑定到GridView
,可以执行以下选择查询:
DECLARE @temp NVARCHAR(255); DECLARE @maxLength INT; SET @temp = 'The quick brown fox jumped over the lazy dog.'; SET @maxLength = 10; SELECT CASE WHEN LEN(@temp) > @maxLength THEN SUBSTRING(@temp, 0, @maxLength) + '...' ELSE @temp END
至于修复你的RowDataBound
手头的问题,这也应该工作。 但你不应该进行投射,而是尝试这样做:
protected void Ds_my_projects_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.Cells[1].Text.ToString().Length > 200) { e.Row.Cells[1].Text = e.Row.Cells[1].Text.ToString().Substring(0, 200) + "..."; } } }
GridView在模板字段中的列备注显示为“备注…”,工具提示将显示为全文。
<%# Eval("description").ToString().Length>100? (Eval("description") as string).Substring(0,100)+"..." : Eval("description") %>
我尝试了这个代码,它运行正常。 将以下代码添加到.aspx页面:
<%#Eval("Body").ToString().Length > 125 ? (Eval("Body").ToString().Substring(0,125))+"........": Eval("Body") %>