如何在gridview中显示前100个字符?

时间:2011-03-08 15:22:50

标签: c# asp.net gridview string

我使用gridview来显示数据,但有时数据很大,可以在单元格中显示。我可以使用方法来允许gridview显示f.e.一个字符串的前100个字符?

欢迎任何帮助!

3 个答案:

答案 0 :(得分:5)

您可以处理gridview的RowDataBound事件并剪切文本长度,如下所示:

protected void gvNotes_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex < 0)
        return;

    int _myColumnIndex = 0;   // Substitute your value here

    string text = e.Row.Cells[_myColumnIndex].Text;

    if (text.Length > 100)
    {
        e.Row.Cells[_myColumnIndex].Text = text.Substring(0, 100);
    }
}

答案 1 :(得分:0)

对于IE唯一的答案,你可以使用CSS,只要你有一个列的设置宽度,设置溢出:省略号或溢出:隐藏(应该适用于所有浏览器),如果你不想要点。


好的,根据评论,我暂时没有使用gridviews,但是要为每个单元格和类中设置一个CSS类:

trimText
{
   overflow:ellipsis;
}

还有一些黑客攻击可以让它显示跨浏览器 - 这里有一些注意事项:

http://www.jide.fr/english/emulate-text-overflowellipsis-in-firefox-with-css

答案 2 :(得分:0)

创建此功能

public object TrimString(string input, int length)
    {
        // return nothing if the string is null
        if (String.IsNullOrEmpty(input))
        {
            return string.Empty;
        }

        // invalid length submitted
        if (length <= 0)
        {
            length = 100;
        }

        if (input.Length > length)
        {
            return input.Substring(0, length) + "...";
        }

        return input;
    }

你可以从你的aspx页面中调用它。

<ItemTemplate>
        <asp:Label ID="Label4" runat="server" Text='<%# TrimString(Eval("CustName").ToString(),100) %>'></asp:Label>
</ItemTemplate>