Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)归海一刀published in(发表于) 2014/1/30 1:10:12 多种方法实现超长字符用-.....-代替_[Asp.Net教程]
1、gridview效果如图:
公用方法:protected string Intercept(string sInput) { if (sInput != null && sInput != string.Empty) { if (sInput.Length > 10) return sInput = sInput.Substring(0, 10) + "..."; else return sInput; } return ""; }第一种方法:在GridView的RowDataBound方法中遍历每一行数据;
protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e) { string sGUID; if (e.Row.RowType == DataControlRowType.DataRow) { sGUID = e.Row.Cells[0].Text; //display the changed values e.Row.Cells[0].Text = Intercept(sGUID); } } 第二种方法:将GridView的某一列(改变默认显示)变成模板列;
具体步骤:GridView右键-显示智能标记-编辑列-在选定的字段里面选中字段(右下角点击将此字段转换为TemplateField)(如果你从第一个方法试到第二个方法,第二个方法完成后运行,你会发现编号这行没有数据显示,知道为什么吗?)答案就是第一种方法里面已经改变了显示效果(cs代码),如果你再次在html代码调用Intercept(...)方法将return "",所以没有数据显示;
*注意:这里将某一列变成了模板列的时候,Html代码绑定该字段是:Text='<%# Bind("GUID") %>',这里若要运用上面的公用方法(Intercept(...)),将Bind改成Eval,具体代码请看:
第三种方法最简单:通过CSS样式来控制;在html中加入样式表
相信大多数人会喜欢这种,不用编写代码;
2.DataList
第一种方法:在ItemDataBound(...)方法中遍历所有行protected void dlMain_ItemDataBound(object sender, DataListItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Label lblGUID = (Label)e.Item.FindControl("lblGUID"); System.Data.Common.DbDataRecord dbdr = (System.Data.Common.DbDataRecord)e.Item.DataItem; //这里可以改变任何一列的数据显示 string sGUID = Convert.ToString(dbdr["GUID"]); lblGUID.Text = Intercept(sGUID); } } 第二种方法:也是通过CSS样式来控制;
同上;
赞