Limit text size in GridView column

谁都会走 提交于 2019-12-18 06:13:40

问题


I have an asp:GridView declared as follows:

<asp:GridView runat="server" id="dg_myprojects" AllowSorting="true" AutoGenerateColumns="false" Width="900px" CssClass="Grid" OnSorting="TaskGridView_SortingMine" OnRowCommand="MyProjectList_RowCommand" DataKeyNames="project_id" OnRowDataBound="Ds_my_projects_RowDataBound">
    <AlternatingRowStyle CssClass="alternateRow" />
    <HeaderStyle CssClass="GridHeader" />
    <Columns>
        <asp:BoundField DataField="project_name" HeaderText="Project Name" SortExpression="project_name"/>
        <asp:BoundField DataField="description" HeaderText="Description" SortExpression="description" ItemStyle-HorizontalAlign="Left" />
        <asp:BoundField DataField="role" HeaderText="Role" SortExpression="role" />
        <asp:BoundField DataField="start_date" HeaderText="Start Date" SortExpression="start_date" DataFormatString="{0:d}"/>
        <asp:BoundField DataField="end_date" HeaderText="End Date" SortExpression="end_date" DataFormatString="{0:d}" />
        <asp:BoundField DataField="client" HeaderText="Client" SortExpression="client" />
        <asp:TemplateField>
        <ItemTemplate>
             <asp:LinkButton ID="DeleteButton" CommandArgument='<%# Eval("project_id") %>' CommandName="Remove" runat="server">Remove</asp:LinkButton>
        </ItemTemplate></asp:TemplateField>
        <asp:HyperLinkField DataNavigateUrlFields="project_id" DataNavigateUrlFormatString="EditProject.aspx?pID={0}" Text="Edit"/>
    </Columns>
</asp:GridView>

My problem is100% aesthetic. The word wrap that happens for long descriptions make the table look tacky. What I want to do with a long description is have an ellipses (...) when the description gets too long

Long description blah blah...

I couldn't find a built in method for this so I decided to try to implement this OnRowDataBound of the GridView.

protected void Ds_my_projects_RowDataBound(object sender, GridViewRowEventArgs e)
{            
   DataRow curRow = ((DataRowView)e.Row.DataItem).Row;
  if (curRow["Description"].ToString().Length > 200)
       curRow["Description"] = curRow["Description"].ToString().Substring(0, 200) + "...";

}

I get an run time exception on the first line because of Object reference not set to an instance of an object.

What am I doing wrong here? Is there a simpler way to accomplish what I'm trying to do?


回答1:


You could handle it with css and by adding this to your Grid css class:

.Grid {
    table-layout:fixed; 
    width:100%; 
}
.Grid .Shorter {
    overflow: hidden; 
    text-overflow: ellipsis; 
    white-space: nowrap;        
}

Update: I modified the above class so that you can affect an individual column by using the ItemStyle-CssClass attribute like so:

<asp:BoundField DataField="description" HeaderText="Description" 
    SortExpression="description" ItemStyle-CssClass="Shorter" />



回答2:


What I would do is create an Extension class that can shorten strings. The static class would have something like the following method:

public static string Shorten(this string name, int chars)
{
    if (name.ToCharArray().Count() > chars)
    {
        return name.Substring(0, chars) + "...";
    }
    else return name;
}

You could then use the BoundFields as TemplateFields like so:

<asp:TemplateField> 
    <ItemTemplate>
        <asp:Label ID="lblDesc" Text="<%# Eval("description").ToString().Shorten(20) %>" />
    </ItemTemplate>
</asp:TemplateField>

The nice thing about this is that you could now use the Shorten() method anywhere.




回答3:


CAbbot has a great suggestion. I've never done it this way but if that works for you, then I like that; simple, elegant, efficient.

The way I've always done it has been through through the DataSource. If you are binding a SqlDataSource to your GridView, you could do a select query like this:

DECLARE @temp NVARCHAR(255);
DECLARE @maxLength INT;
SET @temp = 'The quick brown fox jumped over the lazy dog.';
SET @maxLength = 10;

SELECT CASE WHEN LEN(@temp) > @maxLength THEN SUBSTRING(@temp, 0, @maxLength) + '...' ELSE @temp END

As far as fixing the issue at hand with your RowDataBound, that should work too. But you shouldn't need to do the casting, try this instead:

protected void Ds_my_projects_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[1].Text.ToString().Length > 200)
        {
            e.Row.Cells[1].Text = e.Row.Cells[1].Text.ToString().Substring(0, 200) + "...";
        }
    }
}



回答4:


GridView's Column Remark in Template Field shown as "Remark ..." and Tooltip will show as full text.

 <ItemTemplate>    <asp:Label ID="lblRemark" runat="server" 
                   Text= '<%# Eval("Remark").ToString().Length > 6? (Eval("Remark") as string).Substring(0,6) + " ..." : Eval("Remark")  %>'
                   tooltip = '<%# Eval("Remark") %> '> </asp:Label>
 </ItemTemplate>



回答5:


 <asp:TemplateField HeaderText="Description" SortExpression="description" >
    <ItemTemplate >
      <%# Eval("description").ToString().Length>100? (Eval("description") as string).Substring(0,100)+"..." : Eval("description")  %> 
    </ItemTemplate>
 </asp:TemplateField> 



回答6:


I tried this code and it worked fine. Add the following code to your .aspx page :

        <asp:TemplateField HeaderText="Body" ItemStyle-Width="900px">
            <ItemTemplate >
                <%#Eval("Body").ToString().Length > 125 ? (Eval("Body").ToString().Substring(0,125))+"........": Eval("Body") %>
            </ItemTemplate>
        </asp:TemplateField>


来源:https://stackoverflow.com/questions/7650791/limit-text-size-in-gridview-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!