Winform开发之DataGridView的增删改

DataGridView是一个非常强大的控件,用法很多。这里介绍一个简单的增删改例子。

贴效果图

 Winform开发之DataGridView的增删改_第1张图片

 

右侧输入学生信息点击新增,将数据增加到数据库,并且加载到datagridview中,点击选择某条数据修改,将选择的数据加载到右侧的编辑框内,修改后点击修改即可,也可直接删除。

贴代码

 public partial class Form1 : Form

    {

        private static string strConn = "Data Source=210.26.*.*;Initial Catalog=Test;User ID=sa;Password=****";

        private SqlConnection conn = new SqlConnection(strConn);

        private string sqlId = "";

        private SqlCommand cmd = null;

        private SqlDataAdapter da = null;

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            //SqlDataReader studentlist = cmd.ExecuteReader();

            //bindingSource1.DataSource = studentlist;

            //dataGridView1.DataSource = bindingSource1;

            BindData();

        }

        private void BindData()

        {

            if (conn.State == ConnectionState.Closed)

            {

                conn.Open();

            }

            sqlId = "select * from [Student] ";

            cmd = new SqlCommand(sqlId, conn);

            da = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            da.Fill(ds, "student");

            dataGridView1.AutoGenerateColumns = false;//此行指定不需要自动绑定数据列,数据列在dataGridView的属性items集合里指定,必须放在绑定数据之前哦,放到后面是没用的

            //dataGridView1.DataSource=ds.Tables["Student"];此处直接用DataTalbe绑定,与下面两行代码的效果是一样的

            dataGridView1.DataSource = ds;//使用Dataset,单必须指定DataMember,因为DataSet是DataTable的集合,而datagridview只能绑定一个datatable

            dataGridView1.DataMember = "Student";

            if (conn.State == ConnectionState.Open)

            {

                conn.Close();

            }

        }

        private void btnAdd_Click(object sender, EventArgs e)

        {

            try

            {

                string username = textBox1.Text;

                string homeaddress = textBox2.Text;

                string info = textBox3.Text;

                conn.Open();

                //准备一个SQL语句,其中以@开头的在这里只表示一种变量,一种参数。

                sqlId = "Insert into Student(StudenTnAME, HomeAddress, Content)values(@StudenTnAME,@HomeAddress,@Content)";

                //创建一个参数数组,并且用花括号里面的值来初始化数组

                SqlParameter[] parameters = new[]

                 {

                    //这里也有个初始化的过程,将name复制给@name,下面的是一样的

                    new SqlParameter("@StudenTnAME",username),//而小括号右边的name就是程序一开始我们得到的用户输入的值

                    new SqlParameter("@HomeAddress",homeaddress),

                    new SqlParameter("@Content",info)

                 };

                cmd=conn.CreateCommand();

                //利用对象的属性,把sql字符串放进命令(设置要对数据源执行的SQL语句)

                cmd.CommandText = sqlId;

                //先利用对象的Parameters属性获取参数集,再将参数集的值附加到后面

                cmd.Parameters.AddRange(parameters);

                int x=cmd.ExecuteNonQuery();

                if (x ==)

                {

                    //如果添加成功,那么给用户提示一下

                    MessageBox.Show("添加成功");

                    textBox1.Text = "";

                    textBox2.Text = "";

                    textBox3.Text = "";

                } 

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            finally

            {

                conn.Close();

            }

        }

        //点击选中行,将内容放到编辑框内

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

        {

            textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["studentname"].Value.ToString();

            textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells["homeaddress"].Value.ToString();

            textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells["info"].Value.ToString();

        }

        //对修改该内容进行保存

        private void btnUpdate_Click(object sender, EventArgs e)

        {

            try

            {

                conn.Open();

                //准备一个SQL语句,拼接一个sql串,这里有别于ADD里面传参

                sqlId = "update Student set StudenTnAME='" + textBox1.Text + "',HomeAddress='" + textBox2.Text + "',Content='" + textBox3.Text + "' where ID=" + Convert.ToInt32(dataGridView1.CurrentRow.Cells[].Value.ToString());

                cmd = conn.CreateCommand();

                //利用对象的属性,把sql字符串放进命令(设置要对数据源执行的SQL语句)

                cmd.CommandText = sqlId;

                int x = cmd.ExecuteNonQuery();

                if (x == )

                {

                    //如果添加成功,那么给用户提示一下

                    MessageBox.Show("修改成功");

                    textBox1.Text = "";

                    textBox2.Text = "";

                    textBox3.Text = "";

                    BindData();

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            finally

            {

                conn.Close();

            }

        }

        //删除选中行

        private void btnDel_Click(object sender, EventArgs e)

        {

            try

            {

                conn.Open();

                //准备一个SQL语句,拼接一个sql串,这里有别于ADD里面传参

                sqlId = " delete from Student where ID=" +Convert.ToInt32(dataGridView1.CurrentRow.Cells[].Value.ToString());

                cmd = conn.CreateCommand();

                //利用对象的属性,把sql字符串放进命令(设置要对数据源执行的SQL语句)

                cmd.CommandText = sqlId;

                int x = cmd.ExecuteNonQuery();

                if (x == )

                {

                    //如果添加成功,那么给用户提示一下

                    MessageBox.Show("删除成功");

                    textBox1.Text = "";

                    textBox2.Text = "";

                    textBox3.Text = "";

                    BindData();

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            finally

            {

                conn.Close();

            }

        }       

    }

你可能感兴趣的:(c#,c#)