我想在GridView的第3列的内容只显示前10个字,在加“...”。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text.Length > 10)
{
e.Row.Cells[2].Text = e.Row.Cells[2].Text.Substring(0, 10) + "...";
}
else
{
e.Row.Cells[2].Text=e.Row.Cells[2].Text
}
}
}
我这样做,可是e.Row.Cells[2].Text取不到值,e.Row.Cells[2].Text.Length值是0
怎么回事?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text.Length > 10)
{
e.Row.Cells[2].Text = e.Row.Cells[2].Text.Substring(0, 10) + "...";
}
else
{
e.Row.Cells[2].Text=e.Row.Cells[2].Text
}
}
}
我这样做,可是e.Row.Cells[2].Text取不到值,e.Row.Cells[2].Text.Length值是0
怎么回事?
你写一个方法,直接写到页面上,不用这么复杂StrLength 这个方法就是处理字符串的,写到cs文件中。
protected string StrLength (string str)
{
if (str.Length > 10)
{
return str.Substring(0, 10) + "...";
}
else
{
return str;
} }GridView 中用模板列<asp:TemplateField>
<ItemTemplate>
<%# StrLength(DataBinder.Eval(Container.DataItem,"title").ToString())%>
</ItemTemplate>
</asp:TemplateField>
支持楼上的````
但如果是 BoundField 就不可用了```
最好还是在数据库里面直接栽掉...
select case when len(field)>10 then left(field,10)+'...' else field end as news_name,news_id from tablename
<ItemStyle Width="120px" HorizontalAlign="Left" />
<HeaderStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<div title=\"\" style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap; PADDING-TOP: 1px; PADDING-RIGHT: 1px; PADDING-LEFT: 1px; PADDING-BOTTOM: 1px; width:100px;">
<%# Eval("Name")%>
</div>
</ItemTemplate>
</asp:TemplateField>
如果是 你的方法可行
如果cell[2]列是<asp:TemplateField>
那么直接cell[2].Text是不行得
必须转化为对应控件然后Textprotected void GridView1_RowDataBound ( object sender, GridViewRowEventArgs e )
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
if ( ( ( Label ) e.Row.Cells [ 3 ].FindControl ( "Hehe" ) ).Text.Length > 1 )
{
( ( Label ) e.Row.Cells [ 3 ].FindControl ( "Hehe" ) ).Text = ( ( Label ) e.Row.Cells [ 3 ].FindControl ( "Hehe" ) ).Text.Substring ( 0, 1 ) + "...";
}
}
}
<asp:TemplateField HeaderText="Hehe">
<ItemTemplate>
<asp:Label ID="Hehe" runat="server" Text=<%#Eval("job_id").ToString().Substring(0,1)+"..."%>>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>