无法使用 WPF Datagrid 和 DataAdapter 更新本地数据库

Can't update Local Database using WPF Datagrid & DataAdapter

我试图将 DataGrid 中所做的更改反映到我的本地数据库(SQL 服务器精简版,在本例中)但它失败了。这是代码:

        SqlCeConnection conn;
        SqlCeDataAdapter dataAdapter;

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

    public void Init()
    {
        try
        {
            conn = new SqlCeConnection(@"Data Source = DataModel.sdf");
            dataAdapter = new SqlCeDataAdapter("Select * from Members", conn);
            SqlCeCommandBuilder commandBuilder = new SqlCeCommandBuilder(dataAdapter);
            DataTable dataTable = new DataTable();
            dataAdapter.Fill(dataTable);
            dataTable.RowChanged += dataTable_RowChanged;
            dataTable.RowDeleted += dataTable_RowDeleted;
            membersDataGrid.ItemsSource = dataTable.DefaultView;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }


    }

    void dataTable_RowDeleted(object sender, DataRowChangeEventArgs e)
    {
        dataAdapter.Update(sender as DataTable);
    }

    void dataTable_RowChanged(object sender, DataRowChangeEventArgs e)
    {
        dataAdapter.Update(sender as DataTable);

    }

membersDataGrid 是 UI 中 DataGrid 视图的名称。我做错了什么吗? 提前致谢:-)

这是对我有用的代码。它与您的类似,只是使用我的 localDB 数据库(不是 CE)。另外,请确保在 VS 之外测试您的代码,否则数据库文件可能会在您的 compile/execute 周期中被覆盖,您将永远无法看到您的更改反映在数据库中。

private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
    string connstr = ConfigurationManager.ConnectionStrings["WpfApplication14.Properties.Settings.NorthwindConnectionString"].ToString();
    SqlConnection conn = new SqlConnection(connstr);
    CustomersTableAdapter adapter = new CustomersTableAdapter();
    NorthwindDataSet.CustomersDataTable table = new NorthwindDataSet.CustomersDataTable();

    adapter.Fill(table);
    dataGrid1.ItemsSource = table.DefaultView;

    table.RowChanged += table_RowChanged;
}

void table_RowChanged(object sender, System.Data.DataRowChangeEventArgs e)
{
    using (CustomersTableAdapter adapter = new CustomersTableAdapter())
    {
        adapter.Update(sender as NorthwindDataSet.CustomersDataTable);
    }
}