【问题标题】:Why my update with adapter doesn't work为什么我的适配器更新不起作用
【发布时间】:2011-07-13 13:51:57
【问题描述】:

在关闭表单时,我调用了更新,但收到错误消息:更新需要 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);
        }
    }
}

【问题讨论】:

  • 错误信息是自我解释的......你没有定义一个插入命令。添加 dataAdapter.InsertCommand = connection.CreateCommand() ... 之类的内容,或者,我的建议是,使用 Visual STudio Wizard 生成 85% 的数据访问代码
  • 我只有一个没有数据集的数据表,我不想让向导生成完整的数据集,这太过分了
  • 有点习惯,你可以使用设计器,只生产需要的东西。

标签: c# ms-access ado.net


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-15
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2013-12-28
    相关资源
    最近更新 更多