taji01 taji01 - 1 month ago 7
C# Question

Write first and second column rows in listview inside each row in a text file

I'm using

WinForms
. In my form I have a
listview
and a button. When I click on the button the program writes all of the items in the
listview
into a text file. The problem is that I want the first and second column to be in one line.

Here is my code so far that i use to write to the text file:

using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.WriteLine(item.Text);
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}


My ListView

My list View

Problem output text file

Problem Text file

How I want the text file to display

Goal

Answer

How about just

       using (StreamWriter sw = File.CreateText(DirectoryPath))
        {
            foreach (ListViewItem item in listView1.Items)
            {
                sw.Write(item.Text + ": ");
                for (int i = 1; i < item.SubItems.Count; i++)
                {
                    sw.WriteLine(item.SubItems[i].Text);
                }
            }
         }