Display Line breaks in GridView

This Blog explains the following,
  • How to modify the gridview cell data using RowDataBound
  • How to display line breaks in gridview
I wrote this article specially for ASP.NET beginners. As all we knew that Web browser rendered a  normal line breaks as spaces. So lets discuss how to replace or add line breaks in GridView text.
 
By using CodeBehind 
Simply add a RowDataBound event handler to GridView and create the command this way:
  1. protected void gvMessageList_RowDataBound(object sender, GridViewRowEventArgs e)   
  2. {  
  3.     GridViewRow row = e.Row;  
  4.     if (e.Row.RowType == DataControlRowType.DataRow)   
  5.     {  
  6.         row.Cells[4].Text = row.Cells[4].Text.Replace("\n""<br />");  
  7.     }  
  8. }  
Drawbacks of using the above code:
If the structure of the GridView were to change, this function may break and you must be aware of the final layout of the GridView. This is because it modifies the text in 4th column in the GridView row.
 
By using .aspx
In my opinion, better solution is to simply declare the formatting changes in the same place as the GridView. Here we are using a Template field. 
  1. <asp:TemplateField HeaderText="Team" >  
  2.    <ItemTemplate>  
  3.       <asp:Label ID="lblTeam" runat="server" Text = '<%# Eval(“Team”).ToString().Replace(“\n”, “<br />”) %>' />  
  4.    </ItemTemplate>  
  5. </asp:TemplateField>   
I hope you enjoyed it.
Ebook Download
View all
Learn
View all