为什么我的适配器更新不工作

本文关键字:工作 更新 适配器 我的 为什么 | 更新日期: 2023-09-27 18:02:35

在表单关闭时,我调用update,但我得到错误消息:update需要InsertCommand,而我从这个tut中得到启发http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace datatablemsaccess
{
    partial class Form1
    {
        OleDbDataAdapter dataAdapter;
        private string getSQL() {
            string sql = "SELECT * from tPerson";
            return sql;
        }
        private string getConnectionString() {
            string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @"App_Data'person.mdb";
            return connectionString;
        }
        private DataTable getDataTable(string sql)
        {
            DataTable dataTable;
            string connectionString = getConnectionString();
            using (dataAdapter = new OleDbDataAdapter(sql, connectionString))
            {
                dataTable = new DataTable();
                dataAdapter.Fill(dataTable);
            }
            return dataTable;
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace datatablemsaccess
{
    public partial class Form1 : Form
    {
        BindingSource bindingSource;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            string sql = getSQL();
            bindingSource = new BindingSource();
            bindingSource.DataSource = getDataTable(sql);
            dataGridView1.DataSource = bindingSource;
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            dataAdapter.Update((DataTable)bindingSource.DataSource);
        }
    }
}

为什么我的适配器更新不工作

您需要定义一个InsertCommand。

参见当传递带有新行的DataRow集合时,Update需要一个有效的InsertCommand