sql+datagridview 更新数据库

1. 有时候,会遇到datagridview中cell的值更新了,但是通过SqlDataAdapter.Update(dt)却不能够更新数据,比如在datagridview的cellvaluechanged的事件中直接使用,是不能立即更新的,在cellendedit事件中也是一样,以下是解决办法:

在cellendedit事件中

this.Validate();//有效性,此句很重要

SqlCommandBuilder com = new SqlCommandBuilder(cAdapter);
                com.ConflictOption = System.Data.ConflictOption.OverwriteChanges;
                cAdapter.UpdateCommand = com.GetUpdateCommand();
                cAdapter.DeleteCommand = com.GetDeleteCommand();
                cAdapter.UpdateCommand.Connection = conn;
                cAdapter.DeleteCommand.Connection = conn;
                conn.Open();
                cAdapter.Update(dt);
                dt.AcceptChanges();
                DataSet ds = new DataSet();
                cAdapter.Fill(ds);
                return ds.Tables[0];

2.上述的代码在更改后焦点转移到其他控件时也会出现无法更新的状况,我们就需要在没更新成功时,datagridview能够实时的和数据库保持一致,这样,我们能够知道是否是已经更新成功了,于是下面的函数完好的解决了这个问题

public static DataTable UpdateData(DataTable dt, SqlDataAdapter cAdapter)
        {
            SqlConnection conn = new SqlConnection(Properties.Settings.Default.sqlsource);
            try
            {
                SqlCommandBuilder com = new SqlCommandBuilder(cAdapter);
                com.ConflictOption = System.Data.ConflictOption.OverwriteChanges;
                cAdapter.UpdateCommand = com.GetUpdateCommand();
                cAdapter.DeleteCommand = com.GetDeleteCommand();

 cAdapter.InsertCommand = com.GetInsertCommand();
                cAdapter.UpdateCommand.Connection = conn;
                cAdapter.DeleteCommand.Connection = conn;

cAdapter.InsertCommand.Connection = conn;
                conn.Open();
                cAdapter.Update(dt);
                dt.AcceptChanges();
                DataSet ds = new DataSet();
                cAdapter.Fill(ds);
                return ds.Tables[0];
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("\n更新数据库出错,可能是数据库出现异常,请稍后再试,或者联系管理员解决" + "\n" + ex.Message + "\n" + ex.StackTrace);
                return null;
            }
            finally
            {
                conn.Close();
            }
        }


调用时直接使用datagridview.datasource=DataTable UpdateData(DataTable dt, SqlDataAdapter cAdapter)即可。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值