Saturday, August 21, 2010

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

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.How to show truncated data in grid view in ASP.NET?
%26lt;asp:GridView runat=';server'; ID=';gv'; AutoGenerateColumns=';False';%26gt;


%26lt;Columns%26gt;


%26lt;asp:TemplateField%26gt;


%26lt;ItemTemplate%26gt;


%26lt;%# (Eval(';Name';).ToString().Length %26gt;=10) ? Eval(';Name';).ToString().Substring(0, 10) : Eval(';Name';) %%26gt;


%26lt;/ItemTemplate%26gt;


%26lt;/asp:TemplateField%26gt;





%26lt;/Columns%26gt;


%26lt;/asp:GridView%26gt;








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.





%26lt;%# Eval(';Name';) %%26gt; 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.

No comments:

Post a Comment