Click here to Skip to main content
15,906,341 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Working on a simple project in C#. I have a number of items (5 items in this case) that are all separated by commas. At the end of the line, there is a return and newline (/r/n).

In each of the items separated by commas, I want to have a cell in listview and when I see a return and newline I want to move to the next entry of the list view.

What I am getting is all the text in the first cell and repeats for every cell afterwards.

What I have tried:

private void button2_Click(object sender, EventArgs e)
{
    if (richTextBox2.Lines.Length == 0)
    {
        MessageBox.Show("Load some data First");
        return;
    }

    String richtextstring = String.Empty;

     foreach (string str in richTextBox2.Lines)
     {
         richtextstring = str;

         //try to see if this will discover a comma in the string
        if(richtextstring == ",")
         {
             MessageBox.Show("Comma");
         }
         //try to see if this will discover a hard return
         if(richtextstring == ""\r\n"")
         {
            MessageBox.Show("New Line");
         }

         listView1.Items.Add(richTextBox2.Text);
     }
}
Posted
Updated 20-Jan-18 4:15am
v2

1 solution

What you are currently doing, is checking if a full line is equal to one single comma (richtextstring == ",") or \r\n which won't help if you want to retrieve comma-separated items. Also, a line of .Lines will never be equal to "\r\n" because that is treated as line separator (so not as a part of the line itself) so .Lines will exclude it.

You appear to be interested in two things: the lines of the RichTextBox and the comma-separated items. For the former, you can use .Lines (as you did), and for the latter, you can use .Split(',').

It's not entirely clear when you want to create a new item in the ListView, but if I understand it correctly, you want to create a new item for every comma-separated item and repeat that for each line. You can do that like this:
C#
if (richTextBox2.Lines.Length == 0)
{
    MessageBox.Show("Load some data first");
    return;
}

foreach (string line in richTextBox2.Lines)
{
    string[] commaSeparatedItems = line.Split(',');
    foreach (string item in commaSeparatedItems)
    {
        listView1.Items.Add(item);
        
        // if you want to do something else for each single item, do it here
    }

    // if you want to do something else for each line (after all comma-separated items have been added), do it here
}
If the above is not what you intended, then you can probably transform it into what you actually want to do.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900