zoukankan      html  css  js  c++  java
  • C# winform xml的增删改查

    代码如下:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Windows.Forms;
    using System.Xml.Linq;
    
    namespace XMLAction
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            /// <summary>
            /// 从xml加载用户
            /// </summary>
            /// <param name="dgv">DataGridView</param>
            private void LoadUserData(DataGridView dgv)
            {
                //加载xml文件
                XDocument xDoc = XDocument.Load("UserData.xml");
                //获取根节点
                XElement root = xDoc.Root;
                List<User> list = new List<User>();
                //循环加载用户
                foreach (XElement item in root.Elements("user"))
                {
                    User model = new User(item.Attribute("id").Value.ToString(), 
                        item.Element("name").Value.ToString(), 
                        item.Element("pwd").Value.ToString());
                    list.Add(model);
                }
                dgv.DataSource = list;
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                if (!System.IO.File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"UserData.xml")))//Directory.GetCurrentDirectory(), "UserData.xml")))
                {
                    //MessageBox.Show("程序第一次运行,请先使用[CreateXML.exe]程序完成环境配置");
                    //Application.Exit();
                    //创建xml对象
                    XDocument xDoc = new XDocument();
                    //创建根节点
                    XElement root = new XElement("Users");
                    //添加根节点
                    xDoc.Add(root);
                    //保存xml文件
                    xDoc.Save("UserData.xml");
                }
                dataGridView1.MultiSelect = false;//取消多行
                dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//选中整行
                txtUId.ReadOnly = true;//修改时Id是不可变的
                LoadUserData(dataGridView1);
            }
    
            private void btnRegister_Click(object sender, EventArgs e)
            {
                string id = txtRId.Text.Trim();
                string name = txtRName.Text.Trim();
                string pwd = txtRPwd.Text;
                if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(pwd))
                {
                    MessageBox.Show("请填写注册信息");
                    return;
                }
                //加载xml
                XDocument xDoc = XDocument.Load("UserData.xml");
                //获取根节点
                XElement root = xDoc.Root;
                //搜索当前注册用户ID是否存在
                XElement isHaveUser = root.Elements("user").SingleOrDefault(p => p.Attribute("id").Value.ToString() == id);
                if (isHaveUser == null)
                {
                    //创建user节点对象
                    XElement userElement = new XElement("user");
                    userElement.SetAttributeValue("id", id);
                    //增加两个子节点
                    userElement.SetElementValue("name", name);
                    userElement.SetElementValue("pwd", pwd);
                    //保存user节点
                    root.Add(userElement);
                    xDoc.Save("UserData.xml");
                    MessageBox.Show("成功!注册用户ID为【" + id + "】");
                    LoadUserData(dataGridView1);
                }
                else
                {
                    MessageBox.Show("用户ID【" + id + "】已存在");
                }
            }
    
            //双击DataGridView控件就刷新一次数据
            private void dataGridView1_DoubleClick(object sender, EventArgs e)
            {
                LoadUserData(dataGridView1);
            }
    
            private void btnDelete_Click(object sender, EventArgs e)
            {
                if (MessageBox.Show("确认删除?", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    string id = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
                    //加载xml
                    XDocument xDoc = XDocument.Load("UserData.xml");
                    //获取根节点
                    XElement root = xDoc.Root;
                    try
                    {
                        //获取这个节点
                        XElement userElement = root.Elements("user").Where(p => p.Attribute("id").Value.ToString() == id).Single();
                        //删除这个节点
                        userElement.Remove();
                        //保存操作后的xml文件
                        xDoc.Save("UserData.xml");
                        MessageBox.Show("删除成功");
                        //加载数据
                        LoadUserData(dataGridView1);
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show("删除失败,请刷新后重试:"+ex.Message);
                    }
                }
                else
                    MessageBox.Show("未删除");
            }
    
            //DataGridView行焦点改变
            private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
            {
                string id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
                string name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                string pwd = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
                txtUId.Text = id;
                txtUName.Text = name;
                txtUPwd.Text = pwd;
            }
    
            private void btnUpdate_Click(object sender, EventArgs e)
            {
                string id = txtUId.Text.Trim();
                string name = txtUName.Text.Trim();
                string pwd = txtUPwd.Text;
                //加载xml文件
                XDocument xDoc = XDocument.Load("UserData.xml");
                //获取根节点
                XElement root = xDoc.Root;
                //找到要修改的用户
                try
                {
                    XElement crrentElement = root.Elements("user").Where(p => p.Attribute("id").Value.ToString() == id).Single();
                    crrentElement.SetElementValue("name", name);
                    crrentElement.SetElementValue("pwd", pwd);
                    //完成修改操作后,保存xml文件
                    xDoc.Save("UserData.xml");
                    MessageBox.Show("修改成功");
                    LoadUserData(dataGridView1);
                }
                catch
                {
                    MessageBox.Show("修改失败,请刷新后重试");
                }
            }
    
            private void btnLogin_Click(object sender, EventArgs e)
            {
                string id = txtLId.Text.Trim();
                string pwd = txtLPwd.Text;
                if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(pwd))
                {
                    MessageBox.Show("请填写用户Id和密码");
                    return;
                }
                //加载xml文件
                XDocument xDoc = XDocument.Load("UserData.xml");
                //获取根节点
                XElement root = xDoc.Root;
                try
                {
                    XElement user = root.Elements("user").Where(p => p.Attribute("id").Value.ToString() == id).Single();
                    if (user.Element("pwd").Value.ToString() == pwd)
                        MessageBox.Show("登录成功");
                    else
                        MessageBox.Show("密码错误");
                }
                catch
                {
                    MessageBox.Show("用户不存在");
                }
    
            }
    
        }
    
        public class User
        {
            public User(string id, string name, string pwd)
            {
                this.Id = id;
                this.Name = name;
                this.Pwd = pwd;
            }
            public string Id { get; set; }
            public string Name { get; set; }
            public string Pwd { get; set; }
        }
    
    }
    



  • 相关阅读:
    WebBrowser与console.log()
    winform如何让窗体不显示Icon但在任务栏中显示Icon
    (asp.net)百度浏览器Cookie的神奇bug
    winform无边框窗体点击任务栏最小化
    Paper Reading_Distributed System
    Paper Reading_System for ML
    Paper Reading_Database and Storage System
    Paper Reading_ML for system
    Paper Reading_Computer Architecture
    两万多字长文:人工智能新趋势(CB Insights)
  • 原文地址:https://www.cnblogs.com/myesn/p/c-sharp-winform-xml-CRUD.html
Copyright © 2011-2022 走看看