关闭窗体后,利用StreamWriter保存控件里面的数据

时间:2023-12-22 13:15:02

以保存DataGridView里面的数据为例:

通过窗体增加的数据,没有用数据库保存,可以使用StreamWriter将数据存在临时文件里面,再次打开窗体时写入即可。

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//需要将集合中的数据存储
using (StreamWriter sw=new StreamWriter("save.txt"))
{
foreach (var item in lists)
{
sw.WriteLine(item.Name + "|" + item.StuNo + "|" + item.Age);
}
}
MessageBox.Show("ok");
}
        private void Form1_Load(object sender, EventArgs e)
{
using(StreamReader sr=new StreamReader ("save.txt"))
{
//读取一行数据
string str = sr.ReadLine();
//定义分割之后的数组
string[] splits = null;
while (!string.IsNullOrEmpty(str))
{
splits = str.Split('|');
Student stu = new Student(splits[],Convert.ToInt32(splits[]),Convert.ToInt32( splits[]));
lists.Add(stu);
str = sr.ReadLine();
}
this.dgvStu.DataSource = new BindingList<Student>(lists);
}
}