Last post Jul 16, 2009 05:52 AM by crossbyname
Sep 19, 2006 11:45 AM|tod1d|LINK
It has been awhile since I have manipulated data in a Gridview. I am binding an collection to a Gridview and one of the values contains non-html line breaks (\n). I would like to convert these to html line breaks (<br />). The code below works fine.
protected void gridHistory_RowDataBound(object sender, GridViewRowEventArgs e)
GridViewRow row = e.Row;
if (e.Row.RowType == DataControlRowType.DataRow)
row.Cells.Text = row.Cells.Text.Replace("\n", "<br />");
Is there an "easier"/"better" way of doing it?
Sep 19, 2006 11:46 PM|agolden|LINK
I typically put that type of formatting in the GridView markup, either explicitly if the field is never null, or calling a method to handle the null values and make the replacement.
<%# ((string)Eval("Details")).Replace("\n", "<br/>") %>
<%# FormatString(Eval("Details")) %>
Sep 20, 2006 10:00 AM|tod1d|LINK
Your solution is more aesthtic than mine and it works just as well.
Thank you for the input.
Nov 21, 2006 10:17 AM|Sojan80|LINK
Jul 17, 2007 06:09 PM|butterpecan|LINK
oh my god, you guys are awesome!!
I have tried this problem for two days, but I couldn't figure it out.
Finally, I got it!!
Thank you Aaron
Jul 23, 2008 03:15 PM|emrahustun|LINK
After 6 years,
thank you for solution. i was searching everywhere...
Jul 24, 2008 03:16 PM|emrahustun|LINK
i'm beginner for asp.net.
now i have a problem with this.
<asp:Label ID="Label2" runat="server" Text='<%# ((string)Eval("about")).Replace("\n", "<br/>") %>'></asp:Label>
if about is empty, it's giving an error. how can i use if(Eval("about"))!=null) whit this?
Jul 24, 2008 04:42 PM|conankingofcool|LINK
You can make your own Server-Side function that takes a string as the parameter and does the replace only if the string isn't null and then returns it. Then you can do this.
<asp:Label ID="Label2" runat="server" Text='<%# YourFunction(Eval("about"))
Jul 24, 2008 06:03 PM|emrahustun|LINK
thank you very much.
actually, i tried it before.
if "about" is empty, i thing eval is giving this error. (with or without an if-null function)
so this didn't work too: satirdonusum((string)Eval("about"))
Unable to cast object of type 'System.DBNull' to type 'System.String'.
i can't fix this. can you help?
Jul 24, 2008 08:46 PM|agolden|LINK
A way to work around this is to declare your formatting method to accept an object, then check for DBNull and format appropriately. So, you'd have:
<%# Eval("about") %>
and the formatting method would be something like:
protected string FormatString(object o)
return ((string)o).Replace("\n", "<br/>");
Hope that helps.
Jul 25, 2008 11:33 AM|emrahustun|LINK
Thank you so much Contributor.
Jul 16, 2009 05:52 AM|crossbyname|LINK
Hi, this alternative may be useful for any VB user formating in a DetailsView:
<%#Replace(Container.DataItem("Description"), vbCrLf, "<br>")%>
Thank you Aaron for the starter, helped me work this out.