DataGridView编辑后立即更新到数据库

感悟

弄清这些真不容易,你先要弄清Cell…事件等执行事件.然后你要弄清DataGridView的属性,他的属性太多了.弄全懂是不可能的.你得先弄懂怎么去获取表中的值.这值返回什么属性.
曾想自己弄清属性,自己去敲敲,发现困难太多.就参考了一下.

 private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            cellTempValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        }
        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
              //判断前后是否一样
            if (Object.Equals(cellTempValue, dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
            {
                //如果没有修改,则返回
                return;
            }
            //提示是否修改
            if (MessageBox.Show("确定修改?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.None) != DialogResult.OK)
            {
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellTempValue;
                return;
            }
                 //修改数据库
            string sql = String.Format("update Student set {0} = '{1}' where {2} ='{3}'",
                dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].DataPropertyName,//所选单元格列名
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value,                       //所选单元格修改
                dataGridView1.Columns[0].DataPropertyName,                                    //所选单元格列名
                dataGridView1.Rows[e.RowIndex].Cells[0].Value);                                //所选行的学号
            try
            {
                LoginDAL.SQLHelper sqlHelper = new LoginDAL.SQLHelper();//这是链接数据库类实例化
                int n = sqlHelper.ExecuteNonQuery(sql, CommandType.Text);
                string msg = n > 0 ? "操作成功" : "操作失败";
                MessageBox.Show(msg);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
发布了67 篇原创文章 · 获赞 72 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42957931/article/details/90244677