使用c#中的datagridview和导航器绑定删除和更新ms访问数据库

时间:2013-09-04 07:24:19

标签: c# datagridview

您好我正忙着做一个项目我正在尝试从我的datagridview更新数据并将数据删除到y access数据库中。它确实在datagridview中删除它,但它不会保存数据库中的更改,因此永远不会在真实数据库中更新或删除。谢谢你的帮助。这是y代码:

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

namespace Church_Network
{
    public partial class Form11 : Form
    {
    OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ELPARAISO\Desktop\icons\Church Network1\Church Network1\Church Network\Project.accdb");
    OleDbDataAdapter ad = new OleDbDataAdapter();
    DataSet ProjectDataSet3 = new DataSet();

    public Form11()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        saveToolStripButton.PerformClick();

        MessageBox.Show("updated");
    }

    private void button5_Click(object sender, EventArgs e)
    {
        try
        {
            ad.SelectCommand = new OleDbCommand("select* from Member ", con);
            ProjectDataSet3.Clear();
            ad.Fill(ProjectDataSet3);
            dataGridView1.DataSource = ProjectDataSet3.Tables[0];

           con.Open();
           ad.SelectCommand.ExecuteNonQuery();
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Form11_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'projectDataSet3.Member' table. You can move, or remove it, as needed.
        this.memberTableAdapter.Fill(this.projectDataSet3.Member);
    }

    private void button6_Click(object sender, EventArgs e)
    {
        Form8 f8 = new Form8();
        f8.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        bindingNavigatorDeleteItem.PerformClick();

        MessageBox.Show("deleted");

    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}

}

1 个答案:

答案 0 :(得分:0)

您必须添加用于删除和更新数据库的命令。我在你的代码中看不到这样的东西。

因此,请尝试添加以下内容:

private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
   DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
   int id = drv.Row[0];
   if(drv != null)
   {
       delete(id);
   }
}

public void delete(int id)
{ 
   try 
   {
      con.Open();
      OleDbCommand comm = new OleDbCommand("delete from Member where id=@id", con);
      comm.Parameters.AddWithValue("@id", id);
      comm.ExecuteNonQuery();
   }
   catch(OleDbException ex)
   {
       MessageBox.Show("DataConnection not found!", ex);
   }
   finally
   {
       con.Close();
   }

更新Db需要同样的事情。