对于<asp:BoundColumn></asp:BoundColumn> 绑定列中的字符串长度的限制方法如下:
在ItemDataBound事件中添加如下代码,即可实现字符串长度的限制
private
void
DataGrid1_ItemDataBound(
object
sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
... {
if ((e.Item.ItemType == ListItemType.Item) ||
(e.Item.ItemType == ListItemType.AlternatingItem) ||
(e.Item.ItemType == ListItemType.SelectedItem) )
...{
string strText = e.Item.Cells[1].Text;
e.Item.Cells[1].ToolTip = strText;
if(strText.length > 5)
...{
strText = strText .Substring(0,5);
e.Item.Cells[1].Text = strText + "...";
}
}
}
... {
if ((e.Item.ItemType == ListItemType.Item) ||
(e.Item.ItemType == ListItemType.AlternatingItem) ||
(e.Item.ItemType == ListItemType.SelectedItem) )
...{
string strText = e.Item.Cells[1].Text;
e.Item.Cells[1].ToolTip = strText;
if(strText.length > 5)
...{
strText = strText .Substring(0,5);
e.Item.Cells[1].Text = strText + "...";
}
}
}
由于该方法对<asp:HyperLinkColumn></asp:HyperLinkColumn>的列并不起作用,因此用下面的方法来解决此问题:
在.cs文件中添加如下函数:
protected
string
FormatString(
object
o,
int
length)
... {
string s = o.ToString();
if(s.Length > length)
return s.Substring(0,length) + "";
return s;
}
... {
string s = o.ToString();
if(s.Length > length)
return s.Substring(0,length) + "";
return s;
}
在aspx页面做如下设置:
<
asp:TemplateColumn
>
< HeaderTemplate >
新闻标题
</ HeaderTemplate >
< ItemTemplate >
< asp:HyperLink ID = " HyperLink1 " runat = " server " NavigateUrl = ' <%# DataBinder.Eval (Container,"DataItem.newsid","admin_add_vnews.aspx?id={0}")%> '
Text = ' <%# FormatString(DataBinder.Eval(Container,"DataItem.title"),5)%> '
Target = " _blank "
ToolTip = ' <%# DataBinder.Eval(Container,"DataItem.title")%> ' >
</ asp:HyperLink >
</ ItemTemplate >
</ asp:TemplateColumn >
< HeaderTemplate >
新闻标题
</ HeaderTemplate >
< ItemTemplate >
< asp:HyperLink ID = " HyperLink1 " runat = " server " NavigateUrl = ' <%# DataBinder.Eval (Container,"DataItem.newsid","admin_add_vnews.aspx?id={0}")%> '
Text = ' <%# FormatString(DataBinder.Eval(Container,"DataItem.title"),5)%> '
Target = " _blank "
ToolTip = ' <%# DataBinder.Eval(Container,"DataItem.title")%> ' >
</ asp:HyperLink >
</ ItemTemplate >
</ asp:TemplateColumn >
通过上面介绍的两种方法即可解决此类问题。