方法一:
<script runat="server">
private String leftSubStr(String str, int len)
{
if (str.Length > len)
return str.Substring(0, len) + "...";
else
return str;
}
</script>
在aspx页面添加上面代码,然后把你绑定的字段用这个函数处理,例如:Text='<%# leftSubStr(Convert.ToString(Eval("你的字段")),20) %>'
方法二:
显示一定长度,后面加省略号,然后当鼠标移上去时再显示标题的全部内容,这样就即做到了不影响版面的布局,又做到了标题内容的全部显示.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="RuleId" Width="100%" ShowHeader="False" GridLines="None">
<Columns>
<asp:TemplateField>
<ItemStyle Width="60px" />
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="Green" Text='<%# Eval("RuleOrder") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="规则标题">
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" CssClass="grid1" Height="20px" />
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("HtmlPath") %>' ToolTip='<%...# Eval("RuleTitle")%>'
Text='<%...# Eval("RuleTitle").ToString().Length>16?Eval("RuleTitle").ToString().Substring(0,16)+"...":Eval("RuleTitle") %>' Font-Bold="True"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
从上面的代码可以看出,我绑定Label控件的Text属性的时候用了条件表达式,当数据库中的标题长度大于16时,则截取前16个字符加上省略号进行显示,当小于16时,就全部绑定.ToolTip属性直接帮定标题字段,鼠标移上去就可显示全部标题了。(题外话,如果你作的是新闻发布系统,你也可以在Text属性的后面再加上一个发布日期的绑定字段,这样标题,日期全出来聊,呵呵,可以灵活应用,举一反三)
方法三:
绑定gridview单元格内容过长,用tooltip,单元格截取指定长度,鼠标停留时显示全部内容,
protected void gv_DataBound(object sender, EventArgs e)
{
// if (e.Row.RowIndex == -1) return;
//if (e.Row.RowType == DataControlRowType.DataRow)
// 演示ToolTip,使用GridView自带的ToolTip
for (int i = 0; i < gv.Rows.Count; i++)
{
gv.Rows[i].Cells[3].ToolTip = gv.Rows[i].Cells[3].Text;
if (gv.Rows[i].Cells[3].Text.Length > 6)
gv.Rows[i].Cells[3].Text = gv.Rows[i].Cells[3].Text.Substring(0, 3) + "...";
}
}
或者:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[5].ToolTip = e.Row.Cells[5].Text;
if (e.Row.Cells[5].Text.Length > 8) e.Row.Cells[5].Text = e.Row.Cells[5].Text.Substring(0, 5) + "...";
}
}
注意
如果长字段为超链接按照上述方法tooltip显示不出来
解决方法:先确保要截取的字段已转化为模板
然后:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlk=(HyperLink)e.Row.FindControl("HyperLink1");
hlk.ToolTip = hlk.Text;
if (hlk.Text.Length > 8) hlk.Text = hlk.Text.Substring(0, 5)+"...";
//e.Row.Cells[4].ToolTip = e.Row.Cells[4].Text; ---这只适合Label
//if (e.Row.Cells[4].Text.Length > 8) e.Row.Cells[4].Text = e.Row.Cells[4].Text.Substring(0, 5) + "...";
}
}
方法四:
首先你要用模板列,然后在ItemStyle中写
<DIV STYLE="width: 120px; height: 50px; border: 1px solid blue;
overflow: hidden; text-overflow:ellipsis">
<%# Eval("你的字段名") %>
</DIV>