Johnathan Salmon
Johnathan Salmon

Reputation: 11

How to save data from listview to a text file

So I know this has been asked, but I'm kinda struggling with it. I have a basic windows forms program that stores 4 values to an array, and then display it in a list-view. but now I have a extra button that if I click on it, I just want it to save the stored values and export it to a text file. And will it be easier to just export it directly from the array? And how can I do that?

Thanks in advance.

Upvotes: 1

Views: 7994

Answers (4)

keysl
keysl

Reputation: 2167

Just incase someone still needs it, this is just a thorough version @othiel answer with subitems

        try
        {
            using (System.IO.TextWriter tw = new System.IO.StreamWriter(@"C:\listViewContent.txt"))
            {
                foreach (ListViewItem item in listView1.Items)
                {
                    tw.WriteLine(item.Text);
                    for (int a = 1; a <= 3; a++ ) //the 3 = number of subitems in a listview 
                    {
                        tw.WriteLine(item.SubItems[a].Text);
                    }
                }
            }
        }
        catch {
            MessageBox.Show("TEXT FILE NOT FOUND");
        }

Just make sure to set the listView1 in details.

Upvotes: 1

neeKo
neeKo

Reputation: 4280

And now, with fancy save file dialog! :)

    private void saveButton_Click(object sender, EventArgs e)
    {
        Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
        dlg.FileName = "DumpFile1"; // Default file name
        dlg.DefaultExt = ".txt"; // Default file extension
        dlg.Filter = "Text files (.txt)|*.txt"; // Filter files by extension

        // Show save file dialog box
        Nullable<bool> result = dlg.ShowDialog();

        // Process save file dialog box results
        if (result == true)
        {
            // Save document
            string filename = dlg.FileName;

            File.WriteAllLines(filename, array, Encoding.UTF8); //array is your array of strings
        }
    }

You need to add a reference to PresentationFramework. (Right click on References in Solution Explorer -> Add Reference, in .NET tab select PresentationFramework)

Upvotes: 0

Otiel
Otiel

Reputation: 18743

using (TextWriter tw = new StreamWriter(@"C:\listViewContent.txt")) {
    foreach (ListViewItem item in listView.Items) {
        tw.WriteLine(item.Text);
    }
}

Upvotes: 1

James L
James L

Reputation: 16864

File.WriteAllLines(path, array, Encoding.UTF8);

Upvotes: 3

Related Questions