多種方法實現超長字符用"....."代替

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,具體代碼請看:

<asp:TemplateField HeaderText="編號">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("GUID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Intercept(Eval("GUID").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

第三種方法最簡單:通過CSS樣式來控制;
在html中加入樣式表
<style type="text/css">
.ellipsis
{
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>

<asp:Label ID="Label1" runat="server" CssClass="ellipsis" Width="80px" Text='<%# Bind("GUID") %>'></asp:Label>

相信大多數人會喜歡這種,不用編寫代碼;

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樣式來控制;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章