2011-01-20 31 views
1

我剛開始探索WPF及其關於數據綁定的可能性。與DataSet和ADO.NET的雙向數據綁定

我有一個示例Access數據庫文件,並將其內容放入DataSet。然後我將DataSet綁定到一個Grid(雙向綁定)。我想要實現的是更新已更改的DataSet-Item的基礎數據庫條目。這是我的代碼:

public partial class MainWindow : Window 
{ 
    DataSet sampleDataSet; 
    OleDbDataAdapter adapter; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     InitializeDB(); 
    } 

    private void InitializeDB() 
    { 
     string mdbFile = "./test.mdb"; 
     string connString = string.Format(
      "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile); 
     OleDbConnection conn = new OleDbConnection(connString); 
     adapter = new OleDbDataAdapter("SELECT * FROM Player;", conn); 

     // ---------------------- 
     // **EDIT** inserted update command 

     OleDbCommand cmd = new OleDbCommand("UPDATE Player SET Name = @Name " + 
         "WHERE ID = @ID", conn); 

     cmd.Parameters.Add("@Name", OleDbType.VarChar, 40, "Name"); 
     cmd.Parameters.Add("@ID", OleDbType.Char, 5, "ID"); 

     // set the update command 
     adapter.UpdateCommand = cmd; 

     // **End of EDIT** 
     // ---------------------- 

     sampleDataSet = new DataSet("Player Table"); 
     adapter.Fill(sampleDataSet, "Player"); 

     data1.DataContext = sampleDataSet; 
    } 

    private void data1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
    {    
     if (e.EditAction == DataGridEditAction.Commit) 
     { 
      adapter.Update(sampleDataSet, "Player"); 
     } 
    } 

    // Edit Comment April, 14th - Begin 
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
     //sampleDataSet.AcceptChanges(); 
     adapter.Update(sampleDataSet, "Player"); // Calling update again fixes it, but why? 
    } 
    // Edit Comment April, 14th - End 
} 

我的XAML看起來像這樣:

<Window x:Class="AdoTest.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <DataGrid Name="data1" AutoGenerateColumns="True" ItemsSource="{Binding Mode=TwoWay, Path=Player}" CellEditEnding="data1_CellEditEnding" /> 
</Grid> 

什麼方法在網格中的數據庫文件實際上堅持更改後的值?

回答

1

使用DataAdapter的更新方法。這將要求您使用執行實際插入,更新和刪除的命令來設置InsertMethod,UpdateMethod和DeleteMethod屬性。你也可以使用System.Data.OleDb.OleDbCommandBuilder只要爲您生成的查詢,選擇打一個表(包括其主鍵或至少一個唯一的列) See this too

另一種方式竟被DBE使用實體框架,並有爲您生成查詢。

編輯一想到,你的問題是什麼?你已經這樣做了(除了設置更新,插入和刪除命令。)

Look here看看如何將數據庫與數據集同步

+0

你說得對,我還不知道還有什麼必須完成。所以現在我定義了一個UpdateCommand(稍後將添加Insert和Delete)。然而,現在,我所做的最後一次更新並未持久,例如我做了三個更新,只有前兩個實際存儲到數據庫。關掉一個,有什麼想法? – rdoubleui 2011-01-24 16:55:04