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

以保存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[0],Convert.ToInt32(splits[1]),Convert.ToInt32( splits[2]));
                    lists.Add(stu);
                    str = sr.ReadLine();
                }
                this.dgvStu.DataSource = new BindingList<Student>(lists);
            }
        }
原文地址:https://www.cnblogs.com/miaoying/p/5165781.html