Converting new lines into line breaks in C#
December 14, 2009 Leave a comment
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: }