Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone.
I have two textBoxes on the form and one listView.
I want to add items from textBox1.Text to Column1 in listView, and items from textBox2.Text to Column2 in listViev1.
I tried the code below but it's not good enough.

Picture 1 is my result.
Picture 2 is as I would like it to be.
How to do it. Thank you.

Picture 1
https://i.postimg.cc/T33QVYWX/1.png

Picture 2
https://i.postimg.cc/Mp35d2yf/3.png


What I have tried:

C#
private void Add()
       {
           try
           {
               string[] line = textBox2.Lines;
               var Column2 = line.ToString();
               foreach (var Column1 in textBox1.Lines)
                   if (!listView1.Items.ContainsKey(Column1))
                   {
                      listView1.Items.Add(new ListViewItem(new string[] { Column1, Column2 }));
                   }
           }
           catch
           {

           }
       }
Posted
Updated 15-Feb-20 16:07pm
v3

1 solution

This will give you the results you are looking for.

The issue was that you were not specifying which item in line you wanted to display.
C#
try
{
    int counter = 0; // Counter to increment to next item in lastNames
    string[] lastNames; 
    lastNames = textBox2.Lines; // Fills a string array with all the last names in textBox2

    foreach (var Column1 in textBox1.Lines)
    {
        // Selects the corresponding last name at the same index as first name. 
        // This assumes first and last names are in the correct order.
        var Column2 = lastNames[counter]; 

        if (!listView1.Items.ContainsKey(Column1))
        {
            listView1.Items.Add(new ListViewItem(new string[] { Column1, Column2 }));
        }

        counter++; // Increments the counter to the next item in lastNames
    }
}
catch
{

}
 
Share this answer
 
Comments
Member 10410972 16-Feb-20 2:15am    
Thank you very much. It does what I wanted it to do. Thanks again.

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