Limiting text length in GridView-Asp.Net 2.0

How can we limit the text length of an item in the gridview:

For this we can use a helper function which will limit the given text to the specified length and return.

Go through the code snippet:

<asp:TemplateField HeaderText="Description">
     <ItemTemplate>
          <asp:Label ID="lblDescription" runat="server"
                    Text='<%# Limit(Eval("Description"),40) %>' >
          </asp:Label>
     </ItemTemplate>
</asp:TemplateField>

The helper function:

public static string Limit(object Desc, int length)
    {
        StringBuilder strDesc = new StringBuilder();
        strDesc.Insert(0, Desc.ToString());

        if (strDesc.Length > length)
            return strDesc.ToString().Substring(0, length) + "...";
        else return strDesc.ToString();
    }
Advertisements