How to save the ListView contents to a text file?

How to save the ListView contents (including the ColumnHeaders) to a text file?

thanks.

Answers


There is nothing in .NET that will do this for you, you need to do the work yourself.

On whatever event will trigger your save: open the file, iterate through the list content writing the text to the file and then close the file. The close can of course be done via using:

using (var tw = new StreamWriter(filename)) {
  foreach (ListViewItem item in listView.Items) {
    tw.WriteLine(item.Text); 
  }
}

If you want to export all the subitems you must use this code:

 StringBuilder sb;

 if (listView.Items.Count > 0)
 {
     // the actual data
     foreach (ListViewItem lvi in listView.Items)
     {
         sb = new StringBuilder();

         foreach (ListViewItem.ListViewSubItem listViewSubItem in lvi.SubItems)
         {
             sb.Append(string.Format("{0}\t", listViewSubItem.Text));
         }
         sw.WriteLine(sb.ToString());
     }
     sw.WriteLine();
 }

This should work 100%, I made this for a project of mine. I know this is 4 years too late but here it is.

        private void export2File(ListView lv, string splitter)
        {
            string filename = "";
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title = "SaveFileDialog Export2File";
            sfd.Filter = "Text File (.txt) | *.txt";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                filename = sfd.FileName.ToString();
                if (filename != "")
                {
                    using (StreamWriter sw = new StreamWriter(filename))
                    {
                        foreach (ListViewItem item in lv.Items)
                        {
                            sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
                        }
                    }
                }
            }
        }

Need Your Help

GetSubRect(roi).Convert<Bgr, Byte>() throws an exception

c# kinect emgucv

I wrote a code for selecting an area out of a Kinect picture (see below). This area should be defined as ROI of an object in the picture. The selection of the area works, but at the line

What alternatives are there to ClickOnce?

.net wix clickonce web-deployment

I've used ClickOnce a lot over the years, but I have run up against a lot of its limitations. What alternatives are there for web deployment?