通讯录c#实现 课程作业二

寒假 完善一下 用数据库来存储数据 这样 增删查改方便些

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myContracts
{
    public class StudentInfo //新建学生类
    {
        public int StudentId
        {
            set;get;
        }

        public string Name
        {
            set;get;
        }

        public string Sex
        {
            set;get;
        }
        
        public int Age
        {
            set;get;
        }

        public DateTime BirthDate
        {
            set;get;
        }

        public string Phone
        {
            set;get;
        }

        public string HomeAddress
        {
            set;get;
        }

        public string Email
        {
            set;get;
        }

        public string Profession
        {
            set;get;
        }
        
    }
}
StudentInfo

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace myContracts
{
    public class StudentInfoBLL
    {
        //xml文件路径
        private static string _basePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            + @"/xml/Students.xml";

        //创建学生xml文档
        public static void CreateStudentXml()
        {
            XDocument studentDoc = new XDocument();

            XDeclaration xDeclaration = new XDeclaration("1.0", "utf - 8", "yes");//xml版本
            studentDoc.Declaration = xDeclaration;
            XElement xElement = new XElement("studentcontract");//创建studentstore节点

            studentDoc.Add(xElement);
            studentDoc.Save(_basePath);

        }

        //创建学生xml文档 给定位置
        public static void CreateStudentXml(String _Path)
        {
            XDocument studentDoc = new XDocument();

            XDeclaration xDeclaration = new XDeclaration("1.0", "utf - 8", "yes");//xml版本
            studentDoc.Declaration = xDeclaration;//创建studentstore节点
            XElement xElement = new XElement("studentcontract");//根节点为studentcontract

            studentDoc.Add(xElement);
            studentDoc.Save(_Path);
        }
       

        //增加学生信息
        public static bool AddStudentInfo(StudentInfo param)
        {
            XElement xml = XElement.Load(_basePath);

            XElement studentXml = new XElement("student");//创建根节点为student的xml流 并保存学生信息

            studentXml.Add(new XAttribute("studentid", param.StudentId));//将学生学号绑定为表单的主键
            studentXml.Add(new XElement("name", param.Name));
            studentXml.Add(new XElement("sex", param.Sex));
            studentXml.Add(new XElement("age", param.Age.ToString()));
            studentXml.Add(new XElement("birthdate", param.BirthDate.ToString("yyyy-MM-dd")));
            studentXml.Add(new XElement("phone", param.Phone));
            studentXml.Add(new XElement("homeaddress", param.HomeAddress));
            studentXml.Add(new XElement("email", param.Email));
            studentXml.Add(new XElement("profession", param.Profession));
            xml.Add(studentXml);
            xml.Save(_basePath);
            return true;
        }

        //修改学生信息
        public static bool UpdateStudentInfo(StudentInfo param)
        {
            bool result = false;
            if (param.StudentId > 0)
            {
                XElement xml = XElement.Load(_basePath);

                XElement studentXml = (from db in xml.Descendants("student")
                                       where db.Attribute("studentid").Value
                                        == param.StudentId.ToString()
                                       select db).Single();
                studentXml.SetElementValue("studentid", param.StudentId);
                studentXml.SetElementValue("name", param.Name);
                studentXml.SetElementValue("sex", param.Sex);
                studentXml.SetElementValue("age", param.Age.ToString());
                studentXml.SetElementValue("birthdate", param.BirthDate.ToString("yyyy-MM-dd"));
                studentXml.SetElementValue("phone", param.Phone);
                studentXml.SetElementValue("homeaddress", param.HomeAddress);
                studentXml.SetElementValue("email", param.Email);
                studentXml.SetElementValue("profession", param.Profession);
                xml.Save(_basePath);
                result = true;
            }
            return result;
        }

        //删除学生信息
        public static bool DeleteStudentInfo(int studentid)
        {
            bool result = false;
            if (studentid > 0)
            {
                XElement xml = XElement.Load(_basePath);
                XElement studentXml = (from db in xml.Descendants("student")
                                       where db.Attribute("studentid").Value == studentid.ToString()
                                       select db).Single();
                studentXml.Remove();
                xml.Save(_basePath);
                result = true;
            }
            return result;
        }

        //查询学生列表
        public static List<StudentInfo> GetAllStudentInfo()
        {
            List<StudentInfo> studentList = new List<StudentInfo>();
            XElement xml = XElement.Load(_basePath);
            var studentVar = xml.Descendants("student");
            studentList = (from student in studentVar
                           select new StudentInfo
                           {
                               StudentId = Int32.Parse(student.Attribute("studentid").Value),
                               Name = student.Element("name").Value,
                               Age = Int32.Parse(student.Element("age").Value),
                               Sex = student.Element("sex").Value,
                               BirthDate = DateTime.Parse(student.Element("birthdate").Value),
                               Phone = student.Element("phone").Value,
                               HomeAddress = student.Element("homeaddress").Value,
                               Email = student.Element("email").Value,
                               Profession = student.Element("profession").Value

                           }).ToList();
            studentList.Sort(delegate (StudentInfo x, StudentInfo y)
            {
                return x.StudentId.CompareTo(y.StudentId);
            });//按照学号排序
            return studentList;
        }

        //根据学号查询学生信息
        public static StudentInfo GetStudentInfo(int studentid)
        {
            StudentInfo studentinfo = new StudentInfo();
            XElement xml = XElement.Load(_basePath);
            studentinfo = (from student in xml.Descendants("student")
                           where student.Attribute("studentid").Value
                            == studentid.ToString()
                           select new StudentInfo
                           {
                               StudentId = Int32.Parse(student.Attribute("studentid").Value),
                               Name = student.Element("name").Value,
                               Age = Int32.Parse(student.Element("age").Value),
                               Sex = student.Element("sex").Value,
                               BirthDate = DateTime.Parse(student.Element("birthdate").Value),
                               Phone = student.Element("phone").Value,
                               HomeAddress = student.Element("homeaddress").Value,
                               Email = student.Element("email").Value,
                               Profession = student.Element("profession").Value

                           }).Single();
            return studentinfo;
        }

        //获取列表
        public static List<StudentInfo> GetStudentInfoList(StudentInfo param)
        {
            List<StudentInfo> studentList = new List<StudentInfo>();
            XElement xml = XElement.Load(_basePath);

            var studentVar = xml.Descendants("student");
            if(param.StudentId != 0)
            {
                studentVar = xml.Descendants("student").Where(a => a.Attribute("studentid").Value == param.StudentId.ToString());
            }
            else if(!String.IsNullOrEmpty(param.Name))
            {
                studentVar = xml.Descendants("student").Where(a => a.Element("name").Value == param.Name);
            }
            else if (!String.IsNullOrEmpty(param.Profession))
            {
                studentVar = xml.Descendants("student").Where(a => a.Element("profession").Value == param.Profession);
                //studentVar = studentVar;
            }
            else if (!String.IsNullOrEmpty(param.Sex))
            {
                studentVar = xml.Descendants("student").Where(a => a.Element("sex").Value == param.Sex);
            }
            studentVar = studentVar;
            studentList = (from student in studentVar
                           select new StudentInfo
                           {
                               StudentId = Int32.Parse(student.Element("studentid").Value),
                               Name = student.Element("name").Value,
                               Age = Int32.Parse(student.Element("age").Value),
                               Sex = student.Element("sex").Value,
                               BirthDate = DateTime.Parse(student.Element("birthdate").Value),
                               Phone = student.Element("phone").Value,
                               HomeAddress = student.Element("homeaddress").Value,
                               Email = student.Element("email").Value,
                               Profession = student.Element("profession").Value
                           }).ToList();
            return studentList;
        }

        //备份保存
        public static bool Backup()
        {
            String localFilePath = "";
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "xml files(*.xml)|*.xml";
            saveFile.FileName = "Students_Backup";
            saveFile.DefaultExt = "xml";
            saveFile.RestoreDirectory = true;
            saveFile.Title = "请选择备份文件的保存位置";

            DialogResult result = saveFile.ShowDialog();
            if (result == DialogResult.OK)
            {
                XElement xml = XElement.Load(_basePath);
                localFilePath = saveFile.FileName.ToString();//备份文件保存位置
                //Console.WriteLine(localFilePath);//test 文件位置
                StudentInfoBLL.CreateStudentXml(localFilePath);
                xml.Save(localFilePath);
                return true;
            }
            return false;
       
        }

        public static bool Recover()
        {
            String localFilePath = "";
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "xml files(*.xml)|*.xml";
            openFile.DefaultExt = "xml";
            openFile.RestoreDirectory = true;
            openFile.Title = "请选择备份文件";
            DialogResult result = openFile.ShowDialog();
            if (result == DialogResult.OK)
            {
                localFilePath = openFile.FileName.ToString();//备份文件保存的位置
                // Console.WriteLine(localFilePath);test 文件位置
                XElement xml = XElement.Load(localFilePath);
                xml.Save(_basePath);
                return true;
            }
            return false;
        }

    }
}
StudentInfoBLL

 

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;

namespace myContracts
{
    public partial class Form_Main : Form
    {
        public Form_Main()
        {
            InitializeComponent();
            initContracts();
        }

        void initContracts()
        {
            if(File.Exists(AppDomain.CurrentDomain.SetupInformation.ApplicationBase+@"/xml/Students.xml"))
            {
                dataGridView1.DataSource = StudentInfoBLL.GetAllStudentInfo();
            }
            else
            {
                StudentInfoBLL.CreateStudentXml();
                dataGridView1.DataSource = StudentInfoBLL.GetAllStudentInfo();
            }
            dataGridView1.Columns[0].HeaderText = "学生编号";
            dataGridView1.Columns[1].HeaderText = "学生姓名";
            dataGridView1.Columns[2].HeaderText = "学生性别";
            dataGridView1.Columns[3].HeaderText = "学生年龄";
            dataGridView1.Columns[4].HeaderText = "出生日期";
            dataGridView1.Columns[5].HeaderText = "手机号码";
            dataGridView1.Columns[6].HeaderText = "家庭地址";
            dataGridView1.Columns[7].HeaderText = "电子邮箱";
            dataGridView1.Columns[8].HeaderText = "专    业";

        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            Form_Add formadd = new Form_Add();
            formadd.ShowDialog();
            initContracts();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 1)
            {
                int selectrow = Int32.Parse(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex]
                    .Cells[0].Value.ToString());
                Form_Edit formedit = new Form_Edit();
                formedit.studentid_edit = selectrow;
                formedit.ShowDialog()
; initContracts();
            }
            else
                MessageBox.Show("请选中一行后再点击编辑按钮!");
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("确定要删除此学生信息?","确认信息", MessageBoxButtons.YesNo, MessageBoxIcon.Warning
                , MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                int selectrow = Int32.Parse(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex]
                    .Cells[0].Value.ToString());
                if (StudentInfoBLL.DeleteStudentInfo(selectrow))
                    MessageBox.Show("删除学生信息成功!");
                else
                    MessageBox.Show("删除学生信息失败,请检查是否选中学生信息!");
                initContracts();
            }
            else
                MessageBox.Show("请选中一行后再点击删除按钮!");
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            Form_Search formsearch = new Form_Search();
            formsearch.ShowDialog();
        }

        private void Form_Main_Load(object sender, EventArgs e)
        {

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (StudentInfoBLL.Backup())
            {
                MessageBox.Show("信息导出成功!", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (StudentInfoBLL.Recover())
            {
                initContracts();
                MessageBox.Show("信息导入成功!", "导入成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if( (sender as TreeView) != null)
            {
                treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
            }
        }

        private void treeView1_MouseClick(object sender, MouseEventArgs e)
        {
            
            if(treeView1.SelectedNode.Text == "计算机科学与技术")
            {
                StudentInfo s = new StudentInfo();
                s.Profession = "计算机科学与技术";
                dataGridView1.DataSource = StudentInfoBLL.GetStudentInfoList(s);
            }
            else if(treeView1.SelectedNode.Text == "信息安全")
            {
                StudentInfo s = new StudentInfo();
                s.Profession = "信息安全";
                dataGridView1.DataSource = StudentInfoBLL.GetStudentInfoList(s);
            }
            else if(treeView1.SelectedNode.Text == "电子信息科学与技术")
            {
                StudentInfo s = new StudentInfo();
                s.Profession = "电子信息科学与技术";
                dataGridView1.DataSource = StudentInfoBLL.GetStudentInfoList(s);
            }
            else if(treeView1.SelectedNode.Text == "" )
            {
                StudentInfo s = new StudentInfo();
                s.Sex = "";
                dataGridView1.DataSource = StudentInfoBLL.GetStudentInfoList(s);
            }
            else if(treeView1.SelectedNode.Text == "")
            {
                StudentInfo s = new StudentInfo();
                s.Sex = "";
                dataGridView1.DataSource = StudentInfoBLL.GetStudentInfoList(s);
            }
            else
            {
                dataGridView1.DataSource = StudentInfoBLL.GetAllStudentInfo();
            }
            
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            MessageBox.Show("08163343 张钰炳","作者", MessageBoxButtons.OK);
        }
    }
}
Form1

 

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 myContracts
{
    public partial class Form_Add : Form
    {
        public Form_Add()
        {
            InitializeComponent();
        }


        private void Form_Add_Load(object sender, EventArgs e)
        {

        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            StudentInfo s = new StudentInfo();
            s.StudentId = Int32.Parse(txt_id.Text);
            s.Name = txt_name.Text;
            if (rb_man.Checked)
                s.Sex = "";
            else if (rb_woman.Checked)
                s.Sex = "";
            s.Age = Int32.Parse(txt_age.Text);
            s.BirthDate = DateTime.Parse(dateTimePicker1.Text);
            s.Phone = txt_phone.Text;
            s.Email = txt_email.Text;
            s.HomeAddress = txt_home.Text;
            s.Profession = txt_profession.Text;
            if (StudentInfoBLL.AddStudentInfo(s))
            {
                MessageBox.Show("添加学生信息成功");
            }
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
Form2

 

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 myContracts
{
    public partial class Form_Edit : Form
    {
        public int studentid_edit = 0;
        public Form_Edit()
        {
            InitializeComponent();
        }
        public void initControl()
        {
            StudentInfo s = StudentInfoBLL.GetStudentInfo(studentid_edit);
            if (s != null)
            {
                txt_id.Text = s.StudentId.ToString();
                txt_name.Text = s.Name;
                if (s.Sex == "")
                {
                    rb_man.Checked = true;
                    rb_woman.Checked = false;
                }
                else if (s.Sex == "")
                {
                    rb_woman.Checked = true;
                    rb_man.Checked = false;

                }
                s.Sex = "";
                txt_age.Text = s.Age.ToString();
                dateTimePicker1.Text = s.BirthDate.ToString();
                txt_phone.Text = s.Phone;
                txt_email.Text = s.Email;
                txt_home.Text = s.HomeAddress;
                txt_profession.Text = s.Profession;
            }
        }

        private void Form_Edit_Load(object sender, EventArgs e)
        {
            initControl();
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            StudentInfo s = StudentInfoBLL.GetStudentInfo(studentid_edit);
            s.StudentId = Int32.Parse(txt_id.Text);
            s.Name = txt_name.Text;
            if (rb_man.Checked)
                s.Sex = "";
            else if (rb_woman.Checked)
                s.Sex = "";
            s.Age = Int32.Parse(txt_age.Text);
            s.BirthDate = DateTime.Parse(dateTimePicker1.Text);
            s.Phone = txt_phone.Text;
            s.Email = txt_email.Text;
            s.HomeAddress = txt_home.Text;
            s.Profession = txt_profession.Text;
            if (StudentInfoBLL.UpdateStudentInfo(s))
            {
                MessageBox.Show("修改学生信息成功!");
            }

        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
Form3

 

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 myContracts
{
    public partial class Form_Search : Form
    {
        public Form_Search()
        {
            InitializeComponent();
        }
        void InitHeadTitle()
        {
            dataGridView1.Columns[0].HeaderText = "学生编号";
            dataGridView1.Columns[1].HeaderText = "学生姓名";
            dataGridView1.Columns[2].HeaderText = "学生性别";
            dataGridView1.Columns[3].HeaderText = "学生年龄";
            dataGridView1.Columns[4].HeaderText = "出生日期";
            dataGridView1.Columns[5].HeaderText = "手机号码";
            dataGridView1.Columns[6].HeaderText = "家庭地址";
            dataGridView1.Columns[7].HeaderText = "电子邮箱";
            dataGridView1.Columns[8].HeaderText = "专    业";
        }



        private void Form_Search_Load(object sender, EventArgs e)
        {

        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            if(cb_searchiteam.Text == string.Empty)
            {
                dataGridView1.DataSource = StudentInfoBLL.GetAllStudentInfo();
                InitHeadTitle();
            }
            else
            {
                if(txt_searchtxt.Text != string.Empty)
                {
                    StudentInfo s = new StudentInfo();
                    switch (cb_searchiteam.SelectedIndex)
                    {
                        case 0:s.StudentId = Int32.Parse(txt_searchtxt.Text);
                            break;
                        case 1:s.Name = txt_searchtxt.Text;
                            break;
                    }
                    dataGridView1.DataSource = StudentInfoBLL.GetStudentInfoList(s);
                    InitHeadTitle();
                }
                else
                {
                    MessageBox.Show("请输入要查询的" + cb_searchiteam.Text);
                }
            }
        }
    }
}
Form4

 

posted @ 2018-01-10 12:49  Draymonder  阅读(218)  评论(0编辑  收藏  举报