使用 WPF 数据网格更新 SQL 数据库表

Posted

技术标签:

【中文标题】使用 WPF 数据网格更新 SQL 数据库表【英文标题】:Updating SQL database table using WPF datagrid 【发布时间】:2017-11-06 08:50:37 【问题描述】:

我是 WPF 新手,我正在尝试让数据网格在用户编辑本地 SQL 数据库中的表时自动更新它。

我觉得我已经接近了,因为我已经让插入工作,但我无法弄清楚更新(或删除,但我还没有研究那么多)。

我正在为网格使用一个表适配器,它为更新命令调用一个存储过程。我的问题是当我在CurrentCellChanged事件中调用它的更新命令时,它没有传入存储过程的ID参数,所以更新失败。

以下是 WPF xaml.vb 页面的相关代码:

Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("AARP_Conn").ToString)
' construct the dataset
Dim dataset As New AARPDataSet
' use a table adapter to populate the Customers table
Dim adapter As New AARPDataSetTableAdapters.tblRiskTiersTableAdapter

Private Sub _grdRiskTiers_CurrentCellChanged(sender As Object, e As EventArgs) Handles _grdRiskTiers.CurrentCellChanged
    'this line gets error: upRiskTier expects parameter @ID, which was not supplied.
    adapter.Update(dataset.tblRiskTiers)
End Sub


Private Sub RiskTiersForm_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

        adapter.Fill(dataset.tblRiskTiers)

        ' use the dataset  as the DataContext for this Window
        Me.DataContext = dataset.tblRiskTiers.DefaultView

End Sub

这是数据网格标记:

<DataGrid x:Name="_grdRiskTiers" AutoGenerateColumns="False" ItemsSource="Binding" HorizontalAlignment="Left" Margin="45,20,0,0" VerticalAlignment="Top" Height="199" Width="192" Grid.ColumnSpan="2">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="Binding ID" ></DataGridTextColumn>
                <DataGridTextColumn Binding="Binding LowTierCreditScore" Header="Low Tier Credit Score"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>

这里是更新的存储过程:

CREATE PROCEDURE [dbo].[upRiskTier]
    @ID as int,
    @NewLowTierCreditScore as int
AS
IF EXISTS(SELECT * FROM tblRiskTiers WHERE LowTierCreditScore = @NewLowTierCreditScore) BEGIN
    DELETE FROM tblRiskTiers WHERE ID = @ID
END ELSE BEGIN
    UPDATE tblRiskTiers SET LowTierCreditScore = @NewLowTierCreditScore
    WHERE ID = @ID
END

如何获取更新命令以将 ID 传递给存储过程?

更新:以下更新的代码解决了我的问题

Private Sub RiskTiersForm_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

adapter.Fill(dataset.tblRiskTiers)

Dim command = New SqlCommand("[dbo].[upRiskTier]")
command.CommandType = System.Data.CommandType.StoredProcedure
command.Connection = oConn
command.Parameters.Add("@ID", System.Data.SqlDbType.Int, 5, "ID")
command.Parameters.Add("@NewLowTierCreditScore", System.Data.SqlDbType.Int, 5, "LowTierCreditScore")
adapter.Adapter.UpdateCommand = command
' use the Customer table as the DataContext for this Window
Me.DataContext = dataset.tblRiskTiers.DefaultView

End Sub

【问题讨论】:

【参考方案1】:

此错误“此行出错:upRiskTier 需要参数@ID,但未提供该参数。”意思是-您的适配器配置不正确..您的adapter.UpdateCommand中的列和参数之间没有关系...

在下一个示例中显示如何设置 DataTable 中的列和命令参数之间的关系。检查配置 SqlDataAdapter 的代码。

   // Create the UpdateCommand.
    command = new SqlCommand(
        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
        "WHERE CustomerID = @oldCustomerID", connection);

    // Add the parameters for the UpdateCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    SqlParameter parameter = command.Parameters.Add(
        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.UpdateCommand = command;

在你的情况下 - 你的命令应该是

command = new SqlCommand("[dbo].[upRiskTier]");
command.CommandType = CommandType.StoredProcedure;

更详细的可以在MSDN的文章中看到

【讨论】:

我真的不明白为什么这会起作用,因为我已经在我的数据集中的列中设置参数并且插入已经以这种方式工作,但是像这样在代码中创建更新命令确实解决了它.

以上是关于使用 WPF 数据网格更新 SQL 数据库表的主要内容,如果未能解决你的问题,请参考以下文章

使用实体框架核心模型时 WPF 数据网格未更新

使用实体模型和 LINQ 的 C# WPF SQL 多表 CRUD

WPF datagrid 更新数据库

使用可观察对象使用数据库中的数据绑定更新数据网格

WPF XAML - 将数据网格列绑定到外键(数据集)

如何重新加载 WPF 网格