• 步步为营-23-通过GridView实现增删改


    说明:把xml中的数据放入到数据源list中然后显示到gridview中,参考上一节内容

    1 UI页面 

    2创建student类

     public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
            public char Gender { get; set; }
           
        }
    Student

    3把Person.xml放置debug目录下

    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;
    using System.Xml;
    
    namespace XML_GridView
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                //1创建存储对象集合
                List<Student> listStudents = new List<Student>();
    
                //开始读取数据 赋值给集合中的对象
                XmlDocument doc = new XmlDocument();
                doc.Load("Person.xml");
    
                //获得根节点
                XmlElement person = doc.DocumentElement;
                //获取根节点的子节点
                XmlNodeList students = person.ChildNodes;
    
                foreach (XmlNode item in students)
                {
                    //从xml文档中将数据赋值给集合中的Student对象
                    listStudents.Add(new Student(){
                        ID = Convert.ToInt32(item.Attributes["ID"].Value),
                        Name = item["Name"].InnerText,
                        Age = Convert.ToInt32(item["Age"].InnerText),
                        Gender = Convert.ToChar(item["Gender"].InnerText)
                    });
                }
    
                //将数据显示到dataGridView
                dataGridView1.DataSource = listStudents;
            }
        }
    }
    View Code

    4进一步修改UI显示

          //将数据显示到dataGridView
                dataGridView1.DataSource = listStudents;
                //取消第一列
                dataGridView1.RowHeadersVisible = false;
                //单击时,行选中
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

    5新增

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Xml;
    
    namespace XML_GridView
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            //1创建xml对象
            XmlDocument doc = new XmlDocument();
            private void Form1_Load(object sender, EventArgs e)
            {
                //1创建存储对象集合
                List<Student> listStudents = new List<Student>();
    
                //开始读取数据 赋值给集合中的对象
                XmlDocument doc = new XmlDocument();
                doc.Load("Person.xml");
    
                //获得根节点
                XmlElement person = doc.DocumentElement;
                //获取根节点的子节点
                XmlNodeList students = person.ChildNodes;
    
                foreach (XmlNode item in students)
                {
                    //从xml文档中将数据赋值给集合中的Student对象
                    listStudents.Add(new Student(){
                        ID = Convert.ToInt32(item.Attributes["ID"].Value),
                        Name = item["Name"].InnerText,
                        Age = Convert.ToInt32(item["Age"].InnerText),
                        Gender = Convert.ToChar(item["Gender"].InnerText)
                    });
                }
    
                //将数据显示到dataGridView
                dataGridView1.DataSource = listStudents;
                //取消第一列
                dataGridView1.RowHeadersVisible = false;
                //单击时,行选中
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    
                dataGridView1.ClearSelection();
            }
    
            #region 00 单击确定按钮触发事件
            private void btnAdd_Click(object sender, EventArgs e)
            {
                int Id;
                if (!int.TryParse(txtID.Text.Trim(), out Id))
                {
                    MessageBox.Show("ID请输入正整数");
                    return;
                }
                if (File.Exists("Person.xml"))
                {
                    //判断student ID是否存在
                    if (IsExist())
                    {
                        MessageBox.Show("ID已存在");
                        return;
                    }
                    //添加节点                
                    doc.Load("Person.xml");
                    XmlElement person = doc.DocumentElement;
                    AddNode(person);
                }
                else
                {
                    //创建文件--同时把当前页面的Student信息保存到文件中
                    CreateFile();
                }
                doc.Save("Person.xml");
                //刷新界面
                Form1_Load( sender,  e);
                MessageBox.Show("保存成功!");
            } 
            #endregion
            #region 01创建文件
    
            public void CreateFile()
            {
                //1创建声明信息
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                //2创建person根节点
                XmlElement person = doc.CreateElement("Person");
                doc.AppendChild(person);
                AddNode(person);
            }
            #endregion
    
            #region  02添加节点
            private void AddNode(XmlElement person)
            {
                //3创建Student子节点
                XmlElement student = doc.CreateElement("Student");
                person.AppendChild(student);
                //4Student子节点设置属性Id
                student.SetAttribute("ID", txtID.Text.Trim());
                //5Student添加Name节点
                XmlElement name = doc.CreateElement("Name");
                name.InnerText = txtName.Text.Trim();
                student.AppendChild(name);
                //5Student添加Age节点
                XmlElement age = doc.CreateElement("Age");
                age.InnerText = txtAge.Text.Trim();
                student.AppendChild(age);
                //6Student添加Gender节点
                XmlElement gender = doc.CreateElement("Gender");
                if (RDMan.Checked == true)
                {
                    gender.InnerText = "";
                }
                else
                {
                    gender.InnerText = "";
                }
                student.AppendChild(gender);
            }
            #endregion
    
            #region 03判断studentID是否存在
            public bool IsExist()
            {
                doc.Load("Person.xml");
                //1 获取根节点
                XmlElement person = doc.DocumentElement;
                //2 获取所有student的属性
                XmlNodeList students = person.ChildNodes;
                List<string> listID = new List<string>();
                foreach (XmlNode item in students)
                {
                    listID.Add(item.Attributes["ID"].Value);
                }
                if (listID.Contains(txtID.Text))
                {
                    return true;
                }
                return false;
            }
            #endregion
          
        }
    }
    新增

    6 删除

    首先添加一个右击菜单,弹出删除按钮

     #region 04删除按钮触发事件
            private void Delete_Click(object sender, EventArgs e)
            {
                //1获得当前选中行的id
                string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                //2 根据ID进行删除
                doc.Load("Person.xml");
                XmlElement person = doc.DocumentElement;
                XmlNode student = person.SelectSingleNode("/Person/Student[@ID=" + id + "]");
                person.RemoveChild(student);
               
                doc.Save("Person.xml");
                LoadData();
                MessageBox.Show("删除成功");
            } 
            #endregion
    删除

    7修改,添加行双击事件

            #region 05双击后给文本框赋值
            private void Row_DoubleClick(object sender, EventArgs e)
            {
                //将选中行的数据赋值给文本框
                txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                txtAge.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
                string gender = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
                if (gender == "")
                {
                    RDMan.Checked = true;
                }
                else
                {
                    RDFemale.Checked = true;
                }
            } 
            #endregion
    
            #region 06单击确定按钮--进行修改
            private void btnUpdate_Click(object sender, EventArgs e)
            {
                //1ID不可更改
                if (txtID.Text != dataGridView1.SelectedRows[0].Cells[0].Value.ToString())
                {
                    MessageBox.Show("ID不可更改");
                    return;
                }
                
                //2 根据ID进行更新
                doc.Load("Person.xml");
                XmlElement person = doc.DocumentElement;
                XmlNode student = person.SelectSingleNode("/Person/Student[@ID=" + txtID.Text + "]");
                student["Name"].InnerXml = txtName.Text;
                student["Age"].InnerXml = txtAge.Text;
                student["Gender"].InnerXml = RDMan.Checked ? "" : "";           
                doc.Save("Person.xml");
                LoadData();
                MessageBox.Show("修改成功");
            } 
            #endregion
    修改


    总代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Xml;
    
    namespace XML_GridView
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            //1创建xml对象
            XmlDocument doc = new XmlDocument();
            private void Form1_Load(object sender, EventArgs e)
            {
                LoadData();
            }
            
            #region 000DataGridView加载数据
            private void LoadData()
            {
                //1创建存储对象集合
                List<Student> listStudents = new List<Student>();
    
                //开始读取数据 赋值给集合中的对象
                XmlDocument doc = new XmlDocument();
                doc.Load("Person.xml");
    
                //获得根节点
                XmlElement person = doc.DocumentElement;
                //获取根节点的子节点
                XmlNodeList students = person.ChildNodes;
    
                foreach (XmlNode item in students)
                {
                    //从xml文档中将数据赋值给集合中的Student对象
                    listStudents.Add(new Student()
                    {
                        ID = Convert.ToInt32(item.Attributes["ID"].Value),
                        Name = item["Name"].InnerText,
                        Age = Convert.ToInt32(item["Age"].InnerText),
                        Gender = Convert.ToChar(item["Gender"].InnerText)
                    });
                }
    
                //将数据显示到dataGridView
                dataGridView1.DataSource = listStudents;
                //取消第一列
                dataGridView1.RowHeadersVisible = false;
                //单击时,行选中
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    
                dataGridView1.ClearSelection();
            } 
            #endregion
    
            #region 00 单击确定按钮触发事件
            private void btnAdd_Click(object sender, EventArgs e)
            {
                int Id;
                if (!int.TryParse(txtID.Text.Trim(), out Id))
                {
                    MessageBox.Show("ID请输入正整数");
                    return;
                }
                if (File.Exists("Person.xml"))
                {
                    //判断student ID是否存在
                    if (IsExist())
                    {
                        MessageBox.Show("ID已存在");
                        return;
                    }
                    //添加节点                
                    doc.Load("Person.xml");
                    XmlElement person = doc.DocumentElement;
                    AddNode(person);
                }
                else
                {
                    //创建文件--同时把当前页面的Student信息保存到文件中
                    CreateFile();
                }
                doc.Save("Person.xml");
                //刷新界面
                LoadData();
                MessageBox.Show("保存成功!");
            } 
            #endregion
            #region 01创建文件
    
            public void CreateFile()
            {
                //1创建声明信息
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                //2创建person根节点
                XmlElement person = doc.CreateElement("Person");
                doc.AppendChild(person);
                AddNode(person);
            }
            #endregion
    
            #region  02添加节点
            private void AddNode(XmlElement person)
            {
                //3创建Student子节点
                XmlElement student = doc.CreateElement("Student");
                person.AppendChild(student);
                //4Student子节点设置属性Id
                student.SetAttribute("ID", txtID.Text.Trim());
                //5Student添加Name节点
                XmlElement name = doc.CreateElement("Name");
                name.InnerText = txtName.Text.Trim();
                student.AppendChild(name);
                //5Student添加Age节点
                XmlElement age = doc.CreateElement("Age");
                age.InnerText = txtAge.Text.Trim();
                student.AppendChild(age);
                //6Student添加Gender节点
                XmlElement gender = doc.CreateElement("Gender");
                if (RDMan.Checked == true)
                {
                    gender.InnerText = "";
                }
                else
                {
                    gender.InnerText = "";
                }
                student.AppendChild(gender);
            }
            #endregion
    
            #region 03判断studentID是否存在
            public bool IsExist()
            {
                doc.Load("Person.xml");
                //1 获取根节点
                XmlElement person = doc.DocumentElement;
                //2 获取所有student的属性
                XmlNodeList students = person.ChildNodes;
                List<string> listID = new List<string>();
                foreach (XmlNode item in students)
                {
                    listID.Add(item.Attributes["ID"].Value);
                }
                if (listID.Contains(txtID.Text))
                {
                    return true;
                }
                return false;
            }
            #endregion
    
            #region 04删除按钮触发事件
            private void Delete_Click(object sender, EventArgs e)
            {
                //1获得当前选中行的id
                string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                //2 根据ID进行删除
                doc.Load("Person.xml");
                XmlElement person = doc.DocumentElement;
                XmlNode student = person.SelectSingleNode("/Person/Student[@ID=" + id + "]");
                person.RemoveChild(student);
               
                doc.Save("Person.xml");
                LoadData();
                MessageBox.Show("删除成功");
            } 
            #endregion
    
            #region 05双击后给文本框赋值
            private void Row_DoubleClick(object sender, EventArgs e)
            {
                //将选中行的数据赋值给文本框
                txtID.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                txtName.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                txtAge.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
                string gender = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
                if (gender == "")
                {
                    RDMan.Checked = true;
                }
                else
                {
                    RDFemale.Checked = true;
                }
            } 
            #endregion
    
            #region 06单击确定按钮--进行修改
            private void btnUpdate_Click(object sender, EventArgs e)
            {
                //1ID不可更改
                if (txtID.Text != dataGridView1.SelectedRows[0].Cells[0].Value.ToString())
                {
                    MessageBox.Show("ID不可更改");
                    return;
                }
                
                //2 根据ID进行更新
                doc.Load("Person.xml");
                XmlElement person = doc.DocumentElement;
                XmlNode student = person.SelectSingleNode("/Person/Student[@ID=" + txtID.Text + "]");
                student["Name"].InnerXml = txtName.Text;
                student["Age"].InnerXml = txtAge.Text;
                student["Gender"].InnerXml = RDMan.Checked ? "" : "";           
                doc.Save("Person.xml");
                LoadData();
                MessageBox.Show("修改成功");
            } 
            #endregion
    
    
    
    
        }
    }
    View Code
  • 相关阅读:
    一套完整的测试应该由哪些阶段组成?
    测试结束的标准是什么?
    :你的测试职业发展目标是什么?
    您认为做好测试用例设计工作的关键是什么?
    Servlet API中forward()与redirect()的区别?
    AOP 核心概念?
    Spring 中使用了哪些设计模式?
    ArrayList类?
    如何实现拦截器?
    什么是集合?
  • 原文地址:https://www.cnblogs.com/YK2012/p/6727678.html
Copyright © 2020-2023  润新知