2013-02-11 49 views
0

我想创建一个带有数据集的gridview,我在数据绑定之后隐藏了一些列。我还需要显示Descriptin列的前50个字符。我怎样才能做到这一点?这里是我的代码在gridview中显示数据集单元格的子串

protected void grid_all_posts_DataBound(object sender, GridViewRowEventArgs e) 
{ 
    e.Row.Cells[0].Visible = false; 
    e.Row.Cells[1].Visible = false; 

    // I want to display only substring in Gridview 
    e.Row.Cells[3].Text = e.Row.Cells[3].Text.ToString().Substring(0,50); 
} 

我希望这是明确

+0

你有什么问题? – 2013-02-11 18:37:44

+0

对不起。它给出这个错误“System.ArgumentOutOfRangeException:索引和长度必须引用字符串中的位置。” – 2013-02-11 18:39:02

回答

2

而不是只显示字符的定数,你可以考虑使用CSS3 text-overflow财产。使用此属性,可以指定最大宽度(以像素为单位),并显示一个elipses以指示更多文本可用。

<div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width:150px"> 
    <span title="Put your full text here"> 
     This is some really long text. We want it to cut off after a specified number of pixels, and show the elipses to indicate that more text is available. 
    </span> 
</div> 

通过上面的例子,你可以把整个文本的工具提示/称号,这可以当用户将鼠标悬停在该文本进行查看。

0

这个错误是针对SubString方法的。 当字符串长度小于50子串上升例外

与此更换你的最后一行代码:

e.Row.Cells[3].Text = (e.Row.Cells[3].Text.Length>50) ? e.Row.Cells[3].Text.ToString().Substring(0,50) : e.Row.Cells[3].Text; 

此代码首先检查的字符串的长度,如果necessery调用子。