为什么我的datagrid不更新数据库? WPF .NET 4.5

时间:2016-04-20 14:47:42

标签: c# .net wpf .net-4.5

我正在尝试将数据库表绑定到数据网格视图。我只想显示某些字段,省略用户无关的字段,如ID,CREATED_BY,CREATED_ON等。我可以正确加载列表,但更新回DB不起作用。

已编辑 - 清洁代码。

这是我必须加载数据网格视图。 XAML:

<Grid Margin="0">
    <DataGrid x:Name="ProductsDataGrid" AutoGenerateColumns="False" Style="{StaticResource AzureDataGrid}" Background="White" IsTextSearchEnabled="True" Margin="0,0,0,50" RenderTransformOrigin="0.479,0.06">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"  Binding="{Binding FP1_NAME}" Width="Auto"/>
            <DataGridCheckBoxColumn ElementStyle="{DynamicResource MetroDataGridCheckBox}"
                EditingElementStyle="{DynamicResource MetroDataGridCheckBox}"
                Header="Is Needed"
                            />
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="ProductsGridUpdate" Content="update" Style="{StaticResource AccentedSquareButtonStyle}" HorizontalAlignment="Left" Margin="424,280,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="1.453,1.103" Click="ProductsGridUpdate_Click"/>
</Grid>

以下是代码:

private void LoadList()
    {
        //init
        ProductsDataGrid.Items.Clear();
        ProductsDataGrid.BeginInit();
        ProductsDataGrid.ItemsSource = SQLCommands.GR1_DataSet.fp1_food_products;
        ProductsDataGrid.DataContext = SQLCommands.GR1_DataSet.fp1_food_products;
        ProductsDataGrid.EndInit();
    }
#endregion

private void ProductsGridUpdate_Click(object sender, RoutedEventArgs e)
{ // this does not work? No error is thrown, and it runs. DB just doesn't update. 
    SQLCommands.fp1_adapter.Update (SQLCommands.GR1_DataSet.fp1_food_products);
}

以下是我在app启动时运行以准备加载列表的内容:

public static void SQLFoodProductsProvider()
{
    GR1_DataSet = new GroceryListDataSet();

    fp1_adapter = new GroceryListDataSetTableAdapters.fp1_food_productsTableAdapter();
    fp1_adapter.Fill(GR1_DataSet.fp1_food_products);


    //GR1_DataSet.fp1_food_products.fp1_food_productsRowChanged +=
    //    new GroceryListDataSet.fp1_food_productsRowChangeEventHandler(MainWindow.fp1_food_productsRowModified);
    //GR1_DataSet.fp1_food_products.fp1_food_productsRowDeleted +=
    //    new GroceryListDataSet.fp1_food_productsRowChangeEventHandler(MainWindow.fp1_food_productsRowModified);
}

非常感谢任何帮助或方向。先感谢您。如果重要的话,我使用Visual Studio创建了数据库。

1 个答案:

答案 0 :(得分:0)

好。我已经正式过早地秃顶,但我已经弄明白了。在DB对象上,有一个属性,“复制到输出目录”。

默认设置为'Always Copy'。将其设置为'Copy if newer'修复了我的所有问题。

因为在所有StackOverflow帖子(以及其他网站)之外,我会离开,我还没有看到这是一个可能的解决方案。

相关问题