练习:WinForm--DataGridView增删改查完整版

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

namespace DataGridView增删改查完整版.DataConnection
{
    public class DataConnection
    {
        private static string connstr = "server=.; database=mydb; user=sa; pwd=ray; ";
        public static SqlConnection Conn
        {
            get { return new SqlConnection(connstr); }
        }
    }
}

DataConnection

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

namespace DataGridView增删改查完整版.Model
{
    public class Info
    {
        private string _code;
        public string Code
        {
            get { return _code; }
            set { _code = value; }
        }

        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private bool _gender;
        public bool Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }

        private string _nation;
        public string Nation
        {
            get { return _nation; }
            set { _nation = value; }
        }

        private DateTime _birthday;
        public DateTime Birthday
        {
            get { return _birthday; }
            set { _birthday = value; }
        }

        //属性扩展
        public string GenderName
        {
            get { return _gender ? "男" : "女"; }
        }

        public int Age
        {
            get { return DateTime.Now.Year - _birthday.Year; }
        }

        public string NationName
        {
            get
            {
                DataOperation.NationData nd = new DataOperation.NationData();
                return nd.NationName(Nation);
            }
        }

    }
}

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

namespace DataGridView增删改查完整版.Model
{
    public class Nation
    {
        private string _code;

        public string Code
        {
            get { return _code; }
            set { _code = value; }
        }
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }
}

Model

/*
 *InfoData
 */

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

namespace DataGridView增删改查完整版.DataOperation
{
    public class InfoData
    {
        private SqlConnection _conn;
        private SqlCommand _cmd;
        private SqlDataReader _dr;

        public InfoData()
        {
            _conn = DataConnection.DataConnection.Conn;
            _cmd = _conn.CreateCommand();
        }

        /// <summary>
        /// 查询Info表全部数据
        /// </summary>
        /// <returns></returns>
        public List<Model.Info> Select()
        {
            _cmd.CommandText = "select *from Info";
            _conn.Open();
            _dr = _cmd.ExecuteReader();
            List<Model.Info> list = new List<Model.Info>();
            if (_dr.HasRows)
            {
                while (_dr.Read())
                {
                    Model.Info data = new Model.Info();
                    data.Code = _dr["Code"].ToString();
                    data.Name = _dr["Name"].ToString();
                    data.Gender = Convert.ToBoolean(_dr["Sex"]);
                    data.Nation = _dr["Nation"].ToString();
                    data.Birthday = Convert.ToDateTime(_dr["Birthday"]);
                    list.Add(data);
                }
            }
            _conn.Close();
            return list;
        }

        /// <summary>
        /// 查询Info表指定数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Model.Info Select(string code)
        {
            _cmd.CommandText = "select *from Info where [email protected]";
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@code",code);
            _conn.Open();
            _dr = _cmd.ExecuteReader();
            Model.Info data = new Model.Info();
            if (_dr.HasRows)
            {
                while (_dr.Read())
                {
                    data.Code = _dr["Code"].ToString();
                    data.Name = _dr["Name"].ToString();
                    data.Gender = Convert.ToBoolean(_dr["Sex"]);
                    data.Nation = _dr["Nation"].ToString();
                    data.Birthday = Convert.ToDateTime(_dr["Birthday"]);
                }
            }
            _conn.Close();
            return data;
        }

        /// <summary>
        /// 多条件查询Info表中数据
        /// </summary>
        /// <param name="name">姓名</param>
        /// <param name="gender">性别</param>
        /// <param name="age">年龄</param>
        /// <param name="nation">民族</param>
        /// <returns>List<Info></returns>
        public List<Model.Info> Select(string name,string gender,string nation)
        {
            string tjName = " 1=1 ", tjGender = " 1=1 ", tjNation = " 1=1 ";

            //输入姓名
            if (name != "")
            {
                tjName = " Name like @name ";
            }

            //输入性别
            if (gender != "")
            {
                tjGender = " [email protected] ";
            }
            bool genderBool;
            if (gender == "男")
            {
                genderBool = true;
            }
            else { genderBool = false; }

            //选择民族
            string nationcode = "";
            if (nation != "")
            {
                tjNation = " [email protected] ";
                DataOperation.NationData nda=new NationData();
                nationcode = nda.NationCode(nation);
            }

            _cmd.CommandText = "select *from Info where" + tjName + "and" + tjGender+ "and" + tjNation;
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@name", "%" + name + "%");
            _cmd.Parameters.AddWithValue("@gender", genderBool);
            _cmd.Parameters.AddWithValue("@nation", nationcode);

            _conn.Open();
            _dr = _cmd.ExecuteReader();
            List<Model.Info> list = new List<Model.Info>();
            if (_dr.HasRows)
            {
                while (_dr.Read())
                {
                    Model.Info idata = new Model.Info();
                    idata.Code = _dr["Code"].ToString();
                    idata.Name = _dr["Name"].ToString();
                    idata.Gender = Convert.ToBoolean(_dr["Sex"]);
                    idata.Nation = _dr["Nation"].ToString();
                    idata.Birthday = Convert.ToDateTime(_dr["Birthday"]);
                    list.Add(idata);
                }
            }
            _conn.Close();
            return list;
        }

        /// <summary>
        /// 向Info表中添加数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="gender"></param>
        /// <param name="nation"></param>
        /// <param name="birthday"></param>
        public void Insert(string code,string name,string gender,string nation,string birthday)
        {
            DataOperation.NationData nda = new NationData();
            bool genderBool;
            if (gender == "男")
            {
                genderBool = true;
            }
            else { genderBool = false; }

            _cmd.CommandText = "insert into Info values(@code,@name,@gender,@nation,@birthday)";
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@code",code);
            _cmd.Parameters.AddWithValue("@name",name);
            _cmd.Parameters.AddWithValue("@gender", genderBool);
            _cmd.Parameters.AddWithValue("@nation",nda.NationCode(nation));
            _cmd.Parameters.AddWithValue("@birthday",birthday);
            _conn.Open();
            _cmd.ExecuteNonQuery();
            _conn.Close();
        }

        /// <summary>
        /// 修改Info表中数据
        /// </summary>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="gender"></param>
        /// <param name="nation"></param>
        /// <param name="birthday"></param>
        public void Update(string code, string name, bool gender, string nation, string birthday)
        {
            _cmd.CommandText = "update Info set [email protected],[email protected],[email protected],[email protected] where [email protected]";
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@code", code);
            _cmd.Parameters.AddWithValue("@name", name);
            _cmd.Parameters.AddWithValue("@sex", gender);
            _cmd.Parameters.AddWithValue("@nation", nation);
            _cmd.Parameters.AddWithValue("@birthday", birthday);
            _conn.Open();
            _cmd.ExecuteNonQuery();
            _conn.Close();
        }

        public void Delete(string code)
        {
            _cmd.CommandText = "delete from Info where [email protected]";
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@code",code);
            _conn.Open();
            _cmd.ExecuteNonQuery();
            _conn.Close();
        }
    }
}

/*
 * NationData
 */

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

namespace DataGridView增删改查完整版.DataOperation
{
    public class NationData
    {
        private SqlConnection _conn;
        private SqlCommand _cmd;
        private SqlDataReader _dr;

        public NationData()
        {
            _conn = DataConnection.DataConnection.Conn;
            _cmd = _conn.CreateCommand();
        }

        /// <summary>
        /// 民族代号转换民族名称
        /// </summary>
        /// <param name="code">代号</param>
        /// <returns>名称</returns>
        public string NationName(string code)
        {
            _cmd.CommandText = "select Name from Nation where [email protected]";
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@code",code);
            _conn.Open();
            _dr = _cmd.ExecuteReader();
            if (_dr.HasRows)
            {
                _dr.Read();
                return _dr[0].ToString();
            }
            else { return null; }
            _conn.Close();
        }

        /// <summary>
        /// 民族名称转换民族代号
        /// </summary>
        /// <param name="nation">名称</param>
        /// <returns>代号</returns>
        public string NationCode(string name)
        {
            _cmd.CommandText = "select Code from Nation where [email protected]";
            _cmd.Parameters.Clear();
            _cmd.Parameters.AddWithValue("@name", name);
            _conn.Open();
            _dr = _cmd.ExecuteReader();
            if (_dr.HasRows)
            {
                _dr.Read();
                return _dr[0].ToString();
            }
            else { return null; }
            _conn.Close();
        }

        /// <summary>
        /// 查询Nation表信息
        /// </summary>
        /// <returns></returns>
        public List<Model.Nation> Select()
        {
            List<Model.Nation> list = new List<Model.Nation>();
            _cmd.CommandText = "select * from Nation";
            _conn.Open();
            _dr = _cmd.ExecuteReader();
            if (_dr.HasRows)
            {
                while (_dr.Read())
                {
                    Model.Nation data = new Model.Nation();
                    data.Name = _dr["Name"].ToString();
                    list.Add(data);
                }
            }
            _conn.Close();
            return list;
        }
    }
}

DataOperation

主界面:

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 DataGridView增删改查完整版
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //窗体加载执行事件
        private void Form1_Load(object sender, EventArgs e)
        {
            DataOperation.InfoData ida = new DataOperation.InfoData();
            dataGridView1.DataSource = ida.Select();
            dataGridView1.ClearSelection();

            DataOperation.NationData nda = new DataOperation.NationData();
            cmbNation.DataSource = nda.Select();
            cmbNation.DisplayMember = "Name";
            cmbNation.ValueMember = "Code";
        }

        //查询
        private void btnSelect_Click(object sender, EventArgs e)
        {
            string name = txtName.Text;

            string gender;
            if (checkBox1.Checked)
            {
                gender = checkBox1.Text;
                if (checkBox2.Checked)
                {
                    gender = "";
                }
            }
            else if (checkBox2.Checked)
            {
                gender = checkBox2.Text;
            }
            else { gender = ""; }

            string nation = cmbNation.Text;
            if (cmbNation.Text == "请选择")
            {
                nation = "";
            }

            DataOperation.InfoData data = new DataOperation.InfoData();
            dataGridView1.DataSource = data.Select(name, gender, nation);
            dataGridView1.ClearSelection();
        }

        //添加
        private void btnAdd_Click(object sender, EventArgs e)
        {
            FormInsert f = FormInsert.NewInsert();
            f.Show();
            f.Focus();
        }

        //删除
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                MessageBoxButtons btn = MessageBoxButtons.YesNoCancel;
                if (MessageBox.Show("确定删除吗?", "删除数据", btn) == DialogResult.Yes)
                {
                    Model.Info data = dataGridView1.SelectedRows[0].DataBoundItem as Model.Info;
                    DataOperation.InfoData da = new DataOperation.InfoData();
                    da.Delete(data.Code);

                    //刷新数据
                    dataGridView1.DataSource = da.Select();
                    dataGridView1.ClearSelection();
                }
            }
            else { MessageBox.Show("没有选中任何项"); }
        }

        //修改
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                Model.Info data = dataGridView1.SelectedRows[0].DataBoundItem as Model.Info;
                FormUpdate f = FormUpdate.NewUpdate(data.Code);
                f.Show();
                f.Focus();
            }
            else { MessageBox.Show("没有选中任何项"); }
        }

        //Timer刷新页面
        public static int bs = 0;    //定义成员变量用来接收刷新数据
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (bs == 1)
            {
                DataOperation.InfoData da = new DataOperation.InfoData();
                dataGridView1.DataSource = da.Select();
                bs = 0;
                dataGridView1.ClearSelection();
            }
        }

    }
}

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 DataGridView增删改查完整版
{
    public partial class FormInsert : Form
    {
        private FormInsert()
        {
            InitializeComponent();
        }

        private static FormInsert f = null;

        /// <summary>
        /// 返回对象的方法
        /// </summary>
        /// <returns></returns>
        public static FormInsert NewInsert()
        {
            if (f == null || f.IsDisposed)
            {
                f=new FormInsert();
            }
            return f;
        }

        private void FormInsert_Load(object sender, EventArgs e)
        {
            //绑定下拉列表内容
            DataOperation.NationData data=new DataOperation.NationData();
            comboBox1.DataSource = data.Select();
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "Code";
        }

        //添加按钮
        private void button1_Click(object sender, EventArgs e)
        {
            //获取输入数据
            string code = txtcode.Text;
            string name = txtname.Text;
            string gender;
            if (radioButton1.Checked)
            {
                gender = radioButton1.Text;
            }
            else { gender = radioButton2.Text; }
            string nation = comboBox1.Text;
            string birthday = txtbirthday.Text;

            //非空提示
            if (code == "")
            {
                MessageBox.Show("编码不能为空");
            }
            else if( name == "")
            {
                MessageBox.Show("姓名不能为空");
            }
            else if (birthday == "")
            {
                MessageBox.Show("生日不能为空");
            }
            else
            {
                //调用Insert方法,添加数据
                DataOperation.InfoData ida = new DataOperation.InfoData();
                ida.Insert(code, name, gender, nation, birthday);

                //刷新Form1数据
                Form1.bs = 1;

                //关闭当前窗体
                this.Close();
            }
        }
    }
}

FromInsert

修改界面:

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 DataGridView增删改查完整版
{
    public partial class FormUpdate : Form
    {
        //用来存储传递过来的主键值
        private string Code = "";

        private FormUpdate(string code)
        {
            InitializeComponent();
            this.Code = code;
        }

        //用来存储该类的对象
        private static FormUpdate u = null;

        /// <summary>
        /// 返回对象的方法
        /// </summary>
        /// <param name="code">code</param>
        /// <returns></returns>
        public static FormUpdate NewUpdate(string code)
        {
            if (u == null || u.IsDisposed)
            {
                u = new FormUpdate(code);
            }
            return u;
        }

        private void FormUpdate_Load(object sender, EventArgs e)
        {
            //绑定下拉列表数据
            DataOperation.NationData data=new DataOperation.NationData();
            comboBox1.DataSource = data.Select();
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "Code";

            //页面内容初始化
            DataOperation.InfoData idata = new DataOperation.InfoData();
            Model.Info ida = idata.Select(Code);
            txtcode.Text = ida.Code;
            txtname.Text = ida.Name;
            radioButton1.Checked = ida.Gender;
            radioButton2.Checked = !ida.Gender;
            txtbirthday.Text = ida.Birthday.ToString("yyyy-MM-dd");
            comboBox1.Text = ida.NationName;
        }

        //修改按钮
        private void button1_Click(object sender, EventArgs e)
        {
            DataOperation.NationData data = new DataOperation.NationData();
            string codeXG = txtcode.Text;
            string nameXG = txtname.Text;
            bool genderXG = radioButton1.Checked;
            string nationXG = data.NationCode(comboBox1.Text);
            string birthdayXG = txtbirthday.Text;

            DataOperation.InfoData Idata = new DataOperation.InfoData();
            Idata.Update(codeXG, nameXG, genderXG, nationXG, birthdayXG);

            Form1.bs = 1;

            this.Close();
        }
    }
}

FormUpdate

运行界面:

多条件查询:

添加:

删除:

修改:

时间: 2024-10-12 23:00:36

练习:WinForm--DataGridView增删改查完整版的相关文章

WinForm DataGridView增删改查

连接数据库对表进行增删改查 1.绑定数据源 //做一个变量控制页面刷新 public static int bs = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { JianSanDA da = new JianSanDA(); //绑定数据源 dataGridView1.DataSource = da.Select(); //设置不自动生成列 d

WinForm连接数据库增删改查

对象属性 using System; using System.Collections.Generic; using System.Text; namespace LeikuObject { public class TelObject { private int _Code; public int Code { get { return _Code; } set { _Code = value; } } private string _Name; public string Name { ge

asp.net中的DataGridView增删改查加分页

前台页面: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="StaffManager.aspx.cs" Inherits="adminmaster_StaffManager" EnableEventValidation="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTM

ztree--插件实现增删改查demo(完整版)

ztree--插件实现增删改查demo(完整版) var setting = { async: { enable: true,       //开启异步加载处理 dataFilter: filter  //用于对 Ajax 返回数据进行预处理的函数 }, view: { addHoverDom: addHoverDom, removeHoverDom: removeHoverDom, selectedMulti: false, }, check: { enable: false }, data:

winform窗体(六)——DataGridView控件及通过此控件中实现增删改查

DataGridView:显示数据表,通过此控件中可以实现连接数据库,实现数据的增删改查 一.后台数据绑定:    List<xxx> list = new List<xxx>();      dataGridView1.DataSource = list;      //设置不自动生成列,此属性在属性面板中没有      dataGridView1.AutoGenerateColumns = false;      //取消加载默认选中第一行      dataGridView1

C#在winform中操作数据库,实现数据增删改查

1.前言: 运行环境:VS2013+SQL2008+Windows10 程序界面预览: 使用的主要控件:dataGridview和menuStrip等. 2.功能具体介绍: 1.首先,我们要先实现基本的数据操作,增删改查这几个操作. (1)先定义一个数据库操作的公共类: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks

使用DataGridView进行增删改查,并同步到数据库

DataGridView控件具有极高的可配置性和可扩展性.它提供有大量的属性.方法和事件,能够用来对该控件的外观和行为进行自己定义.以下通过一个小样例来展示DataGridView进行增删改查,并同步到数据库的功能. 窗口展示: 用户需求: 1.当窗口显示时,将数据库中用户表中的数据显示出来. 2.选中一行,运行删除操作,同一时候在数据库中对应数据被删除. 3.双击某个数据,进行编辑,或者在空白行加入新的数据,然后点击更新,数据库随之更新. 代码展示: Public Class Form1'代码

DataSet之增删改查操作(DataGridView绑定)

DataSet数据集,数据缓存在客户端内存中,支持断开式连接.DataGridView控件绑定DataSet时,它自动的改变的DS的行的状态,而且在做增删改查的时候,可以借助SqlCommandBuilder类来完成. SqlCommandBuilder必须执行SELECT命令来检索元数据,所以它要求多往返服务器一次,从而增加了应用程序的开销,而且操作的表必须要有主键约束.优点是自动建立insertcommand等命令 1,添加操作 private void button2_Click(obje

winform 窗体实现增删改查(CRUD)共用模式

转载:http://www.csframework.com/archive/2/arc-2-20110617-1632.htm 本站原创文章是有针对性地实现一个功能或一个简单的项目. 有很多刚毕业的学生都有着丰富的理论知识,通过学习本站实例源码,我们相信很快提高您的开发经验.但开发较大型项目,光从实践角度来讲还是不够的,尽管少数学生在校期间开发出一些小软件,总体来讲经验还是不足,需要长时间的积累和学习. 就实现增删改查,不同的开发员会有不同的实现方式.有人会说:不就是实现增删改查嘛,有何难度!邓