我有一个 asp:GridView 声明如下:
<asp:GridView runat="server" id="dg_myprojects" AllowSorting="true" AutoGenerateColumns="false" Width="900px" CssClass="Grid" OnSorting="TaskGridView_SortingMine" OnRowCommand="MyProjectList_RowCommand" DataKeyNames="project_id" OnRowDataBound="Ds_my_projects_RowDataBound">
<AlternatingRowStyle CssClass="alternateRow" />
<HeaderStyle CssClass="GridHeader" />
<Columns>
<asp:BoundField DataField="project_name" HeaderText="Project Name" SortExpression="project_name"/>
<asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" ItemStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="role" HeaderText="Role" SortExpression="role" />
<asp:BoundField DataField="start_date" HeaderText="Start Date" SortExpression="start_date" DataFormatString="{0:d}"/>
<asp:BoundField DataField="end_date" HeaderText="End Date" SortExpression="end_date" DataFormatString="{0:d}" />
<asp:BoundField DataField="client" HeaderText="Client" SortExpression="client" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" CommandArgument='<%# Eval("project_id") %>' CommandName="Remove" runat="server">Remove</asp:LinkButton>
</ItemTemplate></asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="project_id" DataNavigateUrlFormatString="EditProject.aspx?pID={0}" Text="Edit"/>
</Columns>
</asp:GridView>
我的问题是 100% 审美。长描述的自动换行使表格看起来俗气。我想对长描述做的是在描述太长时使用省略号 (...)
Long description blah blah...
我找不到为此的内置方法,所以我决定尝试实现 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) + "...";
}
由于未将对象引用设置为对象的实例,我在第一行收到运行时异常。
我在这里做错了什么?有没有更简单的方法来完成我想做的事情?
最佳答案
您可以使用 css 处理它,并将其添加到您的 Grid
css 类中:
.Grid {
table-layout:fixed;
width:100%;
}
.Grid .Shorter {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
更新:我修改了上面的类,这样您就可以像这样使用 ItemStyle-CssClass 属性来影响单个列:
<asp:BoundField DataField="description" HeaderText="Description"
SortExpression="description" ItemStyle-CssClass="Shorter" />
关于c# - 限制 GridView 列中的文本大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650791/