帮助使用Update(dataTable)更新访问数据库

时间:2011-08-21 23:03:00

标签: c# winforms ms-access datagridview

我到处都看了,但我似乎无法让它发挥作用。

我正在尝试从DataGridView更新Access数据库。将数据库加载到网格中工作正常。我使用了this site中描述的说明。

但是,要根据对DataGridView所做的更改来更新数据库,我使用了命令dataAdapter.Update(datatable);,但是根据位置(此代码旁边),代码会运行,但数据库不会更新。如果我将它放在一个按钮中,则会在插入到语句中引发异常“语法错误”。

其他问题:我应该在加载DataGridView后关闭连接变量吗?如果是这样,我应该重新打开它来执行更新,然后重新关闭它吗?这有什么作用?。

非常感谢任何帮助。 编辑:Tim问全班,

 public partial class Pantalla_Proyecto : Form
{
    private Inicio Inicio;
    private List<string> Logueado;
    private OleDbConnection conn;
    private OleDbDataAdapter Adaptador;
    private DataTable Tabla;
    private BindingSource Bsource;
    private OleDbCommandBuilder Builder;

    public Pantalla_Proyecto(Inicio Inicio, List<string> Logueado)
    {
        this.Inicio =Inicio;
        this.Logueado = Logueado;
        InitializeComponent();
    }
    private void Pantalla_Proyecto_Load(object sender, EventArgs e)
    {
    }

     private void importarCDPToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Importar_CDP Importar_CDP = new Importar_CDP();
        Importar_CDP.Show();
    }

    private void importarListasToolStripMenuItem_Click(object sender, EventArgs e)
    {
        WindowsFormsApplication1.Formularios.Lista_Lazos.Importar_Listas1 Importar_Listas = new WindowsFormsApplication1.Formularios.Lista_Lazos.Importar_Listas1();
        Importar_Listas.Show();
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {

    }

    private void flowLayoutPanel2_Paint(object sender, PaintEventArgs e)
    {

    }

    private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {

    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sql = "Select *  From ["+TABLE (THIS IS A STRING I GET FROM PREVIOUS FORM)+"]";
        conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=proyectos\" + Location(this is a string i get on the previous form) + ".mdb;User Id=admin;Password=;");
        conn.Open();

        //  Extraemos info de mi database y la meto en un datatable
        Adaptador = new OleDbDataAdapter(sql, conn);
        Builder = new OleDbCommandBuilder(Adaptador);
        Tabla = new DataTable();
        Adaptador.Fill(Tabla);

        // LLENO EL DATA GRID VIEW
        Bsource = new BindingSource();
        Bsource.DataSource = Tabla;
        dataGridView1.DataSource = Bsource;
        dataGridView1.Dock = DockStyle.Fill;
        Adaptador.Update(Tabla);//if i put it here nothing happens
        conn.Close();


    }

    private void dataGridView1_Validating(object sender, CancelEventArgs e)
    {

    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        conn.Open();
        Adaptador.Update(Tabla);//IF i put it here i get an exception
        conn.Close();
    }

2 个答案:

答案 0 :(得分:1)

根据OP的请求详细说明using语句,让我们采用comboBox1_SelectedIndexChanged方法:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string sql = "Select *  From ["+TABLE (THIS IS A STRING I GET FROM PREVIOUS FORM)+"]";

    using (conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=proyectos\" + Location(this is a string i get on the previous form) + ".mdb;User Id=admin;Password=;"))
    {
        conn.Open();

        //  Extraemos info de mi database y la meto en un datatable
        Adaptador = new OleDbDataAdapter(sql, conn);
        //  Remove the OleDbCommandBuilder
        Tabla = new DataTable();
        Adaptador.Fill(Tabla);

        // LLENO EL DATA GRID VIEW
        Bsource = new BindingSource();
        Bsource.DataSource = Tabla;
        dataGridView1.DataSource = Bsource;
        dataGridView1.Dock = DockStyle.Fill;
        // ** NOTE:
        // At this point, there's nothing to update - all that
        // has happened is that you've bound the DataTable
        // to the DataGridView.
        Adaptador.Update(Tabla);//if i put it here nothing happens

    } // Your connection will be closed at this point when the using
      // statement goes out of scope.
}

<强>更新

MSDN说“当你创建一个新实例OleDbCommandBuilder时,任何与这个OleDbDataAdapter相关的现有OleDbCommandBuilder都会被释放。”

但是,如果你想完全摆脱OleDbCommandBuilder,你可以这样做(我更新了上面的代码来做到这一点)。既然你认为你遇到了特殊字符的问题,那么这样做可能是值得的。

这样的事情会有所帮助 - 您必须根据表格列的内容修改更新命令:

private void button1_Click_1(object sender, EventArgs e)
{

    conn.Open();        
    Adaptador.UpdateCommand = "<Your SQL here>"  // I.e., UPDATE [TABLE] SET....
    try
    {
        Adaptador.Update((DataTable)Bsource.DataSource);
    }
    catch (Exception ex)
    {
        // Do something with the exception
    }
}

此代码是MSDN的略微修改版本:

How to: Bind Data to the Windows Forms DataGridView Control

请注意,他们在示例中使用了SqlDbCommandBuilder,但总体原则保持不变。

根据David-W-Fenton的评论,您可能希望在Form_Load事件中进行连接和dataadapter初始化,然后关闭Form_Closing事件上的连接。

答案 1 :(得分:0)

首先要检查的是您实际更新的Access文件的运行时路径。

如果您正在使用VS.NET,MDB文件是项目的一部分,并且MDB文件中的“Copy Local”选项设置为true,那么每次运行时都可能是程序覆盖上次执行的更新。

我只是提到因为我被这个人咬了一下; - )

干杯