2013-02-11 23 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調用子。

相關問題