vs2005中通过datagridview更新数据库

 

在通过datagridview更新数据库时,老是提示“当传递具有已修改行的DATAROW集合时,更新要求有效的UPDATECOMMAND 。”的错误,查了网上的N多资料,均语言不详,不能成功更新,后来综合N多资料后,终于可以成功更新数据库了,把代码贴出来以纪念俺的N多辛苦,也为后来人提供参考。      

private Boolean dbUpdate(OleDbDataAdapter adapter, DataGridView dgselect)
        {
            DataTable dtUpdate = new DataTable();
            OleDbCommandBuilder CommandBuiler;
            adapter.Fill(dtUpdate);
            dtUpdate.Rows.Clear();
            System.Data.DataTable dtShow = new System.Data.DataTable();
            DataView dv;
            dv = new DataView();
            dv = (DataView)dgselect.DataSource;
            dtShow = (DataTable)dv.Table;
            int p1 = dtShow.Rows.Count;
            for (int i = 0; i < dtShow.Rows.Count; i++)
            {
                dtUpdate.ImportRow(dtShow.Rows[i]);
            }
            int num = dtUpdate.Rows.Count;
            if (myConnection.State == ConnectionState.Closed)
            {
                myConnection.Open();
            }
            try
            {
                CommandBuiler = new OleDbCommandBuilder(adapter);
                adapter.UpdateCommand = CommandBuiler.GetUpdateCommand();
                adapter.Update(dtUpdate);
                myConnection.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
                return false;
            }

            dtUpdate.AcceptChanges();
            return true;

        }

posted @ 2008-04-20 19:53  choirboy  阅读(5776)  评论(4编辑  收藏  举报