2013-04-08 112 views
2

我有一個表單,我想爲用戶可以從數據庫表「用戶」刪除和編輯(而不是添加)行的目的。我在VS2010中創建了一個表單和一個DataSource,DataSource是使用新的DataSource嚮導創建的。從這裏我拖放DataSourceView窗口中的用戶表的DataGridView到窗體。C#DataGridView(使用數據源填充)不保存到數據庫

我遇到的問題是,當我運行應用程序時,數據將加載到DataGridView罰款,但是當我刪除或編輯一行並單擊保存它不會更新數據庫。

我是一個新手用戶,所以我敢肯定我在做一些愚蠢或天真的事 - 我是否需要在這裏添加一些SQL調用?

任何想法?

enter image description here

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); 
     } 
    } 
} 

回答

0

了更加靈活的方式與您的數據庫來填充你的數據網格視圖是使用一個連接字符串。

在解決方案資源管理器中右鍵單擊您的項目文件並添加一個新項目。添加一個類並將其命名爲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;你的頭在你的Form1的頂部添加。

現在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(); 
相關問題