C#InsertCommand查询

时间:2016-12-10 14:38:38

标签: c# database ms-access datagridview

我有一个连接到我的项目的访问数据库,并希望保存回编辑。只有在修改现有值时,编辑才会保存。当我使用绑定导航器插入行或删除行时,它不会更新我的数据库。我尝试了很多查询:

        try
        {
            query = string.Format("SELECT * FROM {0}", Text);
            adapter.SelectCommand = new OleDbCommand(query, conn);
            adapter.InsertCommand = new OleDbCommand(query, conn);
            adapter.DeleteCommand = new OleDbCommand(query, conn);
            OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);

            adapter.Update(Account);
            Console.WriteLine("Saved");
        }

        catch (Exception ex)
        {
            Console.WriteLine(ex.InnerException + ":" + ex.Message);
        }

在DataGridView.RowAdded事件中,我添加了以下代码:

        try
        {
            string AccNum = accountGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
            string lName = accountGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
            string fName = accountGridView.Rows[e.RowIndex].Cells[2].Value.ToString();
            string balance = accountGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
            adapter.InsertCommand = new OleDbCommand("INSERT INTO " + Text + " VALUES ("
                + AccNum + ", " + lName + ", " + fName + ", " + balance + ")", conn);
            adapter.SelectCommand = new OleDbCommand(query, conn);
            adapter.DeleteCommand = new OleDbCommand(query, conn);
            adapter.Update(Account);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + ":" + ex.InnerException);
        }

在我的RowAdded事件中,它给了我一个错误,在我的常规保存事件中,除插入和删除命令外,一切正常。有谁知道我可以用来使这项工作的查询?

1 个答案:

答案 0 :(得分:0)

我通过删除RowsAdded事件以及所有InsertCommands和DeleteCommands来解决我的问题。我认为问题是我使用错误的SqlCode覆盖了默认的InsertCommands和DeleteCommands。