How to save the ListView contents (i开发者_如何转开发ncluding the ColumnHeaders) to a text file?
thanks.
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);
}
}
}
}
}
精彩评论