简体   繁体   English

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

[英]Can't update Local Database using WPF Datagrid & DataAdapter

I'm trying to reflect the changes being made in the DataGrid to my local database (SQL Server Compact Edition, in this case) but it fails. 我试图将对DataGrid所做的更改反映到本地数据库(在这种情况下为SQL Server Compact Edition),但失败。 Here is the code: 这是代码:

        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 is the name of the DataGrid view in the UI. MembersDataGrid是UI中的DataGrid视图的名称。 Have I done anything wrong? 我做错了什么吗? Thanks in advance :-) 提前致谢 :-)

This is the code that worked for me. 这是对我有用的代码。 It is similar to yours, except that uses my localDB database (not CE). 除使用我的localDB数据库(非CE)外,它与您的相似。 Also, make sure to test your code outside VS, otherwise the database file may get over-written in your compile/execute cycle and you will never be able to see your changes reflected in the database. 另外,请确保在VS外部测试代码,否则数据库文件可能会在编译/执行周期中被覆盖,并且您将永远无法看到更改反映在数据库中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM