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

Posted 庚xiao午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了练习: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 Code=@code";
            _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 = " Sex=@gender ";
            }
            bool genderBool;
            if (gender == "")
            {
                genderBool = true;
            }
            else { genderBool = false; }

            
            //选择民族
            string nationcode = "";
            if (nation != "")
            {
                tjNation = " Nation=@nation ";
                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 Name=@name,Sex=@sex,Nation=@nation,Birthday=@birthday where Code=@code";
            _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 code=@code";
            _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 Code=@code";
            _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 Name=@name";
            _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.Sh

以上是关于练习:WinForm--DataGridView增删改查完整版的主要内容,如果未能解决你的问题,请参考以下文章

winform datagridview 设置交叉色后,再改变某列背景色问题

C# winform datagridview 列顺序的问题?

winform datagridview 改变某行某列的值 怎么做呢

c# winform datagridview cellendedit 在datagridview的第一列输入编码,第二,三列自动取值,名称和规格

winform datagridview 嵌套

c# winform datagridview界面上的行删了,但datagridview数据源没有同步如何解决