How to show truncated data in grid view in ASP.NET?

  • Thread starter Thread starter Crash Overload
  • Start date Start date
C

Crash Overload

Guest
I am using asp.net 2.0. I am using grid view to display data from data base. In grid view for one column i don't want to show all data from database, i want to show only first 10 characters only. i also tried using width property, but it doesn't work.
 
<asp:GridView runat="server" ID="gv" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# (Eval("Name").ToString().Length >=10) ? Eval("Name").ToString().Substring(0, 10) : Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>


Before you truncate the first 10 characters, you need to verify that the string you're truncating is actually more than 10 characters long or you'll get an "IndexOutOfRange Exception"

In the above I assumed that the field you're truncating is called Name.

<%# Eval("Name") %> will return the whole field. In the above, I test if the returned value's length is greater than 10. If yes, I truncated the string to display the first 10 characters. Otherwise, I display all of the field.

For a better approach, you can try to handle the RowDataBound event of the GridView.

Hope this helps.
 
Back
Top