Search code examples
c#listboxclipboardpastelines

Pasting text in a listbox makes it look like it's 1 item, even though it isn't


I have been experiencing an issue with Clipboard and listBox. Here is what my transfer from Clipboard to listBox code looks like:

string s = Clipboard.GetText();
string[] lines = s.Split('\n');
foreach (string ln in lines)
{
    listBox1.Items.Add(ln.Trim());
}

That works perfectly fine and does the job. But the problem is that if I don't copy the text from Excel or Word, or any other text editor really (I copy it from another application, which displays the text in lines), it doesn't display all items on separate line. If I copy the text back it shows the new lines properly. This really bugs me so my question is: can you propose some other way to paste the text into the listBox?


Solution

  • New line is not always represented as "\n". To overcome that, use this:

    .Split(new string[] { "\n", "\r\n" }, StringSplitOptions.None)