1

I have DataTable which contains some strings with "\n" signs. I need to take those strings and put them into DataGridView cells. "\n" should be interpreted as new line.

What I am doing:

dataGridView1.Rows[1].Cells["actionColumn"].Value = subStepLine["action"].ToString();

where subStepLine["action"] is cell in DataTable with string inside "firstLine\n\nsecondLine"

I want to show it in DataGridView as:

"firstLine

secondLine"

but it shows as: "firstLine\n\nsecondLine".

On the other hand, when I am doing is like this:

dataGridView1.Rows[1].Cells["actionColumn"].Value = "firstLine\n\nsecondLine"

then it is fine and '\n\n' are treated as new lines.

I have wrapMode set on true.

Should I set something in DataTable too?

If more code needed I can add it, just dont wanted to do my post unredadable

GohanP
  • 399
  • 2
  • 6
  • 18

1 Answers1

2

If I understood correctly, you wish to have a single cell to display a multi line text, if so, try replacing the \n literals with Environment.NewLine() (that will resolve to \r\n).

This also seems like a duplicate: C#: multiline text in DataGridView control

  • I have seen this, but it did not work. Firstly, just for try, in input I have changed '\n' to '\r\n' to see what will happen but it also wasn't changed into new line. When I wanted to replace '\n' with Environment.NewLine(), by checking `if (subStepLine["action"].ToString().Contains("\n"))` and then do something with this string, then it never goes into this 'if' statement even when there was "\n" string in `subStepLine["action"].ToString()`. – GohanP May 14 '18 at 15:47
  • 1
    That is likely because you did not escape the `\n` Character in your call to Contains. It seems that the string which would not break on the newline character contains **escaped new lines** (\\n instead of \n), try to find and replace those. – AlexMiamorsch May 14 '18 at 15:51
  • Ah, so my problem was with those escaped new lines... I have done it like this `dataGridView1.Rows[firstNewRowIndex].Cells["actionColumn"].Value = subStepLine["action"].ToString().Replace("\\n", Environment.NewLine);` and it works fine. Thanks! – GohanP May 14 '18 at 15:58
  • Glad I could be of help. :) – AlexMiamorsch May 14 '18 at 16:00