Advertisements

Converting new lines into line breaks in C#


As in my last post, I mentioned I am currently working on a project which involves the migration of SQL data into a SharePoint list. In doing so, I have one specific field, which maps to a multi-line rich text field in SharePoint. The data in SQL exists with line breaks, which formats nicely if placed into <pre> </pre> tags in HTML, or within a TEXTAREA element. However, I need this to work within the Rich Text field type within SharePoint, and \r\n’s are not cutting it. That field uses HTML to format the contents.

So, when pushing the items from SQL into the list, you can use the following snippet to replace new line characters [\r\n] with line breaks [<br />]

   1: SPList list = web.Lists["Messages"];
   2:  
   3: // SQL data exists within the referenced DataTable
   4: foreach (DataRow dr in dt.Rows)
   5: {
   6:     SPListItem item = list.Items.Add();
   7:     item["Message"] = dr["Message"].ToString().Replace(Environment.NewLine,"<br />");
   8:     item.Update();
   9: }

 

Advertisements

About Geoff Varosky
Geoff Varosky is a Senior Architect for BlueMetal Architects, based out of Watertown, MA. He has been architecting and developing web based applications his entire career, and has been working with SharePoint for the past 13 years. Geoff is an active member of the SharePoint community, Co-Founder and Co-Organizer of the Boston Area SharePoint Users Group, co-founder for the Boston Office 365 Users Group, co-organizer for SharePoint Saturday Boston and speaks regularly at SharePoint events and user groups.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: