在我的应用程序中,我有一个gridview,其中一列gridview中有一个超链接字段。超链接字段的文本包含几个或多个单词。我想限制该列中显示的字符数。
例如:如果超链接中的文字写着:"大家好,我今天有个问题要问你们"
我希望网格视图栏上的结果是:"大家好,我有…"
当用户点击整条消息时,他们将被重定向到显示整条消息的页面。
我的网格视图如下:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="SerialNumber"
OnRowDataBound="GridView1_RowDataBound"
Width="100%"
ShowFooter="false"
CellPadding="3"
CellSpacing="0"
EnableViewState="false"
AllowPaging="true"
PageSize="28"
AutoPostBack="true">
<Columns>
<asp:BoundField DataField="SrNumber" HeaderText="SrNumber" SortExpression="SrNumber" />
<asp:BoundField DataField="DateAdded" HeaderText="Created on" SortExpression="DateAdded" />
<asp:HyperLinkField DataNavigateUrlFields="SSrNumber" DataNavigateUrlFormatString="showdetail.aspx?SrNumber={0}" DataTextField="text_Det" HeaderText="text_Det" />
<asp:BoundField DataField="DateModified" HeaderText="Last Modified" SortExpression="DateModified" />
<asp:BoundField DataField="CreatedBy" HeaderText="CreatedBy" SortExpression="CreatedBy" />
</Columns>
</asp:GridView>
我的Gridview1_RowDataBound看起来像:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
int _myColumnIndex = 2; // Substitute your value here
string text = e.Row.Cells[_myColumnIndex].Text;
if (text.Length > 10)
{
e.Row.Cells[_myColumnIndex].Text = text.Substring(0, 10);
}
}
问题是:除了超链接字段之外,其他所有列的代码都能正常工作。对于Hyperlinkfiled,它不接受任何数据。字符串文本被混合为null。请帮忙!
谢谢。
我认为您的问题是,您实际上无法使用string text = e.Row.Cells[_myColumnIndex].Text;
语法访问超链接对象本身。
试试这个:
HyperLink myLink = (HyperLink)e.Row.Cells[2].Controls[0];
string text = myLink.Text;
if (text.Length > 10)
{
myLink.Text = text.Substring(0, 10);
}