与DataSet和ADO.NET的双向数据绑定

时间:2011-01-20 14:13:55

标签: wpf data-binding ado.net

我刚刚开始探索WPF及其有关数据绑定的可能性。

我有一个示例Access数据库文件,并将其内容放入DataSet。然后我将DataSet绑定到一个Grid(双向绑定)。我想要实现的是更新已更改的DataSet - 项的基础数据库条目。这是我的代码:

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 个答案:

答案 0 :(得分:1)

使用DataAdapter的更新方法。这将要求您使用执行实际插入,更新和删除的命令设置InsertMethod,UpdateMethod和DeleteMethod属性。只要select选中单个表(包括其主键或至少一个唯一列),您也可以使用System.Data.OleDb.OleDbCommandBuilder为您生成查询 See this too

另一种方法是使用实​​体框架并为您生成查询。

编辑第二个想法,你的问题是什么?您已经这样做了(除了设置更新,插入和删除命令。)

Look here了解如何将数据库与数据集同步

相关问题