截断 ASP.NET GridView 中的文本

use*_*489 1 c# asp.net

这是显示数据库表中所有列和记录的 GridView:

<asp:GridView ID="GridView1" runat="server" AllowPaging="true" BackColor="White" 
        BorderColor="#CCCCCC" BorderWidth="2px" CellPadding="2" CellSpacing="5"
        ForeColor="#000066" GridLines="None">
    <RowStyle BackColor="#F7F7F7" />
    <AlternatingRowStyle BackColor="#E7E7FF" />
    <FooterStyle BackColor="White" />
    <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="White" ForeColor="#000066" 
        HorizontalAlign="Center" />
    <SortedAscendingCellStyle BackColor="#F1F1F1" />
    <SortedAscendingHeaderStyle BackColor="#007DBB" />
    <SortedDescendingCellStyle BackColor="#CAC9C9" />
    <SortedDescendingHeaderStyle BackColor="#00547E" />
    <Columns>
        <asp:CommandField ShowSelectButton="true" HeaderStyle-ForeColor="Yellow"
            ControlStyle-ForeColor="Red" SelectText="Select" HeaderText="Select" />
    </Columns>
</asp:GridView>
Run Code Online (Sandbox Code Playgroud)

背后代码:

public void ShowBooks()
{
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Book", con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView1.DataSource = ds;
    GridView1.DataBind();
}

protected void Page_Load(object sender, EventArgs e)
{
    ShowBooks();
}
Run Code Online (Sandbox Code Playgroud)

在此表上,名为的列Description有很多文本。在 GridView 中,我只想显示 10 或 20 个第一个字符,后跟 ...(三个点)。当我将鼠标悬停在文本上时,我希望全文显示为工具提示。

Uğu*_*maz 5

有两种解决方案可以做到这一点。解决方案在SQL端和代码端。

第一的:

从数据库获取数据时截断描述列值。

SELECT SUBSTRING(Description, 0, 20) FROM Book
Run Code Online (Sandbox Code Playgroud)

SUBSTRING有关T-SQL 中该函数的更多信息请参见此处


第二:

您可以编写一个方法来裁剪字符串值并在GridView. 不要忘记; 为此,首先您应该将Description列字段转换为TemplateField.

辅助类中的 Crop 方法:

public static class StringHelper
{
    public static string Crop(this string text, int maxLength)
    {
        if (text == null) return string.Empty;

        if (text.Length < maxLength) return text;

        return text.Substring(0, maxLength);
    }
}
Run Code Online (Sandbox Code Playgroud)

阿斯克斯侧:

 <asp:TemplateField HeaderText="Description">               
           <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# StringHelper.Crop(Eval("Description").ToString(), 20) %>'></asp:Label>
           </ItemTemplate>
 </asp:TemplateField>
Run Code Online (Sandbox Code Playgroud)

请注意:不要担心空值。null reference exception执行方法时你不会得到ToString()。我已经测试过。


奖金:

如果您不想truncate使用上述选项来应用,您可以使用CSS word-wrap property

GridView 上的描述列:

< asp:BoundField DataField="描述" HeaderText="描述" ControlStyle-CssClass="wrappedText" />

CSS定义:

.wrappedText { word-wrap: break-word; }
Run Code Online (Sandbox Code Playgroud)

请注意,CSS 类名为wrappedText