ASP.Net Programming Tutorial

Ever noticed that an asp.net label control ignores any line returns when your populating it at runtime. The text just comes out as one big paragraph. Well I don’t know if this is the neatest solution and I’m sure some will say there are better ways to do this, but the following code does work.

So say you have some server side code that populates a textbox, something like the following:

Dim ds as dataset = "some datasource"
Dim dr as datarow = ds.tables(0).rows(0)
Me.label1.text = dr.item("Description")

<p>So we’re just basically populating a label with the description field from our table. We know that the description fields contains line feeds but they wont display in the label as it’s just a textarea. Try the following code instead:</p>

Dim ds as dataset = "some datasource"
Dim dr as datarow = ds.tables(0).rows(0)
System.Text.RegularExpressions.Regex.Replace _
(dr.item("Description"), "\n", "<br />", RegexOptions.IgnoreCase)

This basically finds any line feeds in the code (\n) and replaces them with a html line feed. This code can be adapted to search for anything. For example if you wanted to use forum style [b] codes for bold you could do:

System.Text.RegularExpressions.Regex.Replace(fieldname, "[B]", "<strong>", RegexOptions.IgnoreCase)
System.Text.RegularExpressions.Regex.Replace(fieldname, "[/B]", </strong>", RegexOptions.IgnoreCase)

Of course I wouldn’t recommend doing lots of these codes, if you need complex formatting I would recommend using real html in the database. But this might be useful for some minor formatting.

Similar Posts

« »