无法使用WPF Datagrid&更新本地数据库。 DataAdapter的

时间:2015-07-22 01:59:41

标签: c# wpf datagrid ado.net

我试图将DataGrid中所做的更改反映到我的本地数据库(在本例中为SQL Server Compact Edition),但它失败了。这是代码:

        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视图的名称。我做错了什么吗? 在此先感谢: - )

1 个答案:

答案 0 :(得分:1)

这是适合我的代码。它类似于你的,除了使用我的localDB数据库(不是CE)。另外,请确保在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);
    }
}