Geeks With Blogs
Bunch's Blog One day I'll have a catchy subtitle, one day

If you have a GridView that uses BoundFields but does not display line breaks or a lot of spaces quite right here is a way to get around that. This example uses a GridView with one BoundField that uses a DataField of comments. The comments are stored in a database and entered from another page which displays the comments properly in a textbox with all the spaces and line breaks you intended. The trick to get a BoundField to show those items is to take the item and replace the \r\n with a <br /> and the spaces with &nbsp. Also you need to set the HtmlEncode property of the BoundField to false.

This example shows the data being returned to a DataView which is the DataSource for the GridView.

The GridView:

<asp:GridView ID="gvComments" runat="server" AutoGenerateColumns="false" >
      <asp:BoundField DataField="comments" HtmlEncode="false" />

The code (assumes the DataView dv is already filled):

int i = 0;
foreach (DataRow dr in dv.Table.Rows)
   string comment = dr.Field<string>(6);
   comment = comment.Replace(" ", "&nbsp;");
   comment = comment.Replace("\r\n", "<br />");
   dv.Table.Rows[i][6] = comment;

Tags: ,

Posted on Wednesday, May 23, 2012 4:24 PM | Back to top

Comments on this post: BoundField Formatting

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Bunch | Powered by: