【问题标题】:C# DataGridView (populated using a DataSource) not saving to DatabaseC# DataGridView(使用数据源填充)不保存到数据库
【发布时间】:2013-03-30 20:11:06
【问题描述】:

我有一个表单,我希望用户可以从数据库表“用户”中删除和编辑(而不是添加)行。我在 VS2010 中创建了一个表单和一个 DataSource,DataSource 是使用新的 DataSource 向导创建的。从这里我将 DataSource 窗口条中的 Users 表的 DataGridView 拖放到表单中。

我遇到的问题是,当我运行应用程序时,数据会正常加载到 DataGridView 中,但是当我删除或编辑一行并单击保存时,它不会更新数据库。

我是一个新手用户,所以我确定我做了一些愚蠢或幼稚的事情 - 我需要在这里添加一些 sql 调用吗?

有什么想法吗?

public partial class EditUsers : Form
{
    public EditUsers()
    {
        InitializeComponent();
    }

    private void EditUsers_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'debenhamsProjectOfficeDatabaseDataSet.Users' table. You can move, or remove it, as needed.
        this.usersTableAdapter.Fill(this.debenhamsProjectOfficeDatabaseDataSet.Users);

    }

    private void usersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        try
        {
            this.Validate();
            this.usersBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.debenhamsProjectOfficeDatabaseDataSet);
            MessageBox.Show("Update successful");
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

【问题讨论】:

    标签: c# database datagridview save datasource


    【解决方案1】:

    使用数据库填充数据网格视图的更灵活的方法是使用连接字符串。

    在解决方案资源管理器中右键单击您的项目文件并添加一个新项目。添加一个类并将其命名为 connection.cs。在这里输入

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Your_Project_Name
    {
    class Connection
    {
        string ConnectionString;
        public Connection()
        {
            ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
            "Data Source=C:/User/somefolder/Your_Database.accdb;Persist Security Info=False;";
    
        }
        public string getConnection()
        {
            return ConnectionString;
        }
    }
    

    现在将 System.Data.OleDb; 添加到表单顶部的标题中1。

    现在在public partial class EditUsers : Form

    OleDbConnection connect = new OleDbConnection();
            OleDbCommand command = new OleDbCommand();
            OleDbDataReader reader;
            Connection c;
    

    最后在private void EditUsers_Load输入

    c = new Connection();
                connect.ConnectionString = c.getConnection();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      相关资源
      最近更新 更多