【问题标题】:Save the Data Grid Data in Database using WPF and C#使用 WPF 和 C# 将数据网格数据保存在数据库中
【发布时间】:2018-05-18 06:38:47
【问题描述】:

我想将所有数据网格数据保存在数据库中。我从文本框中填充数据网格。如何在WPF C#中一键保存所有数据网格数据在数据库中?

【问题讨论】:

  • 你尝试了什么?
  • 问题不完整!你能显示你的数据网格和数据库表吗?你想在哪里保存数据。
  • 我是 wpf 的新手,但我尝试了这个 foreach (DataGridItem dgi in AddProducts.Items) { string id = dgi.Cells[0].Text;字符串名称 = dgi.Cells[1].Text;但这不起作用,因为在 wpf datagriditem 中不存在
  • 我有 orderdetail 的数据库表,我必须在其中保存产品的价格及其数量和折扣。在我的 wpf 应用程序中,当我单击添加按钮时,我创建了这四个文本框,这些所有值都插入到我的数据网格中而不是数据库中。当我点击确认订单输入其他详细信息后,所有数据都必须保存在数据库中
  • @JIYA 请使用问题左下角的编辑按钮添加这些详细信息和解释。

标签: c# wpf xaml datagrid wpfdatagrid


【解决方案1】:

如果您使用System.Data.DataTable 作为ItemsSourceDataGrid,则将Datagrid 的数据插入到SQL 数据库表中相对容易。使用SqlBulkCopy

using(var conn = new SqlConnection("YourConnectionString"))
{
    var bulkCopy = new SqlBulkCopy(conn)
                    {
                    DestinationTableName =
                        $"[YourSchemaName].[{YourTableName}]"
                    };
    bulkCopy.WriteToServer(((DataView) yourDataGrid.ItemsSource).Table);
}

当然,有一些警告。 DataTable 和目标 SQL 表必须具有相同的结构(列等)。

如果您不使用DataTable 作为您的DataGridItemSource,那么您将必须找到自己的解决方案。

【讨论】:

    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2013-11-02
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多