How can I save the the data in a listview?
For example if the user has put something into the listview and then closes the application, all that information is then lost. Is there any way of saving the information as soon as they put something into the listView?
This is the code I use to input the information from a textbox to the listView1:
string[] items = { titletxt.Text, statustxt.Text };
ListViewItem lvi = new ListViewItem(items);
listView1.Items.Add(lvi);
UPDATE (29/12/2012)
Thanks for all the help! But I can’t seem to get it working. I have created a really simple form to try and get it working. It has 3 textboxes (NameTxt, AgeTxt, HairColourTxt), a button, and the listview(ListOfPeople).
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace listview
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] items = { NameTxt.Text, AgeTxt.Text, HairColourTxt.Text };
ListViewItem lvi = new ListViewItem(items);
ListOfPeople.Items.Add(lvi);
}
}
}
I have tried to add the code posted by @user574632 & @Joe & @DmitryKvochkin and I have changed bits but still cant get it to work. I’m not sure what I’m doing wrong? I have tried to add this:
private void saveListOfPeopleItems(string path, ListView lv)
{
var delimeteredListviewData = new List<string>();
foreach (ListViewItem lvi in lv.Items)
{
string delimeteredItems = string.Empty;
foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems)
{
delimeteredItems += lvsi.Text + "#";
}
delimeteredListviewData.Add(delimeteredItems);
}
System.IO.File.WriteAllLines(path, delimeteredListviewData.ToArray());
}
private void loadListOfPeopleItems(string path, ListView lv)
{
foreach (string line in System.IO.File.ReadAllLines(path))
{
lv.Items.Add(new ListViewItem(line.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries)));
}
}
You need to create the save logic, there’s no automatic method.
The easiest way is to use
Serialization(look forISerializable) to save to a file of your choice (name it whatever you like): You can save entire objects this way. Here is a simple tutorial on serialization.The other method is to parse the listview content into strings (keep only what you need), and you save the strings to a text file (
TextReaderandTextWriter).If you want to save application settings (and not user data), have a look at this link, or this one which might be easier to read.
Finally, if you need to interact with the data you save regularly, or if you have a lot of data to store, use a database (SQL, mySQL, etc). The latter method is the longest one to implement.