WPF应用:DataGrid修改QTY后更新数据库对应字段的实现问询
我来帮你搞定这个WPF数据库操作的实现,结合你的需求一步步拆解:
一、先明确核心需求
咱们的核心操作流程是:
- 用户在TextBox输入编码,按Enter键从数据库拉取对应产品的
Code、Product、Price、QTY数据,展示到DataGrid - 用户修改DataGrid里的
QTY值(比如从1改成3),点击Update按钮后,把数据库中对应记录的QTY字段值减去这个修改后的数值(也就是原QTY = 原QTY - 修改后的QTY) - 还要确保操作的安全性和稳定性,比如防止SQL注入、资源泄漏这些问题
二、完善数据查询逻辑(基于你给出的代码片段)
你原来的Enter键触发查询的代码可以优化下,重点用using自动释放数据库连接,同时用参数化查询避免注入风险,代码如下:
private void txtCode_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { string targetCode = (sender as TextBox).Text.Trim(); if (string.IsNullOrEmpty(targetCode)) { MessageBox.Show("请输入有效的产品编码"); return; } // 使用using语句,自动释放SqlConnection资源,避免连接泄漏 using (SqlConnection con = new SqlConnection("你的数据库连接字符串")) { try { con.Open(); // 参数化查询,防止SQL注入 string query = "SELECT Code, Product, Price, QTY FROM 你的产品表名 WHERE Code = @ProductCode"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@ProductCode", targetCode); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable productTable = new DataTable(); adapter.Fill(productTable); // 将查询结果绑定到DataGrid(假设你的DataGrid命名为dgProducts) dgProducts.ItemsSource = productTable.DefaultView; } catch (Exception ex) { MessageBox.Show($"查询出错:{ex.Message}"); } } } }
三、实现Update按钮的核心逻辑
要完成QTY的更新,首先得确保DataGrid的QTY列是可编辑的,先在XAML里配置DataGrid:
<DataGrid x:Name="dgProducts" AutoGenerateColumns="False" Margin="10"> <DataGrid.Columns> <DataGridTextColumn Header="编码" Binding="{Binding Code}" IsReadOnly="True"/> <DataGridTextColumn Header="产品" Binding="{Binding Product}" IsReadOnly="True"/> <DataGridTextColumn Header="价格" Binding="{Binding Price}" IsReadOnly="True"/> <!-- 设置UpdateSourceTrigger=PropertyChanged,确保修改后立即同步到数据源 --> <DataGridTextColumn Header="数量" Binding="{Binding QTY, UpdateSourceTrigger=PropertyChanged}"/> </DataGrid.Columns> </DataGrid>
然后写Update按钮的点击事件,核心是拿到修改后的QTY值,执行数据库更新:
private void btnUpdate_Click(object sender, RoutedEventArgs e) { // 先判断是否有查询到的数据 if (dgProducts.ItemsSource is DataView productView && productView.Count > 0) { DataRowView currentRow = productView[0]; // 这里假设是单条记录,多条的话需要遍历所有行 string productCode = currentRow["Code"].ToString(); // 验证修改后的QTY是否为有效整数 if (!int.TryParse(currentRow["QTY"].ToString(), out int modifiedQty)) { MessageBox.Show("请输入有效的数量值"); return; } using (SqlConnection con = new SqlConnection("你的数据库连接字符串")) { try { con.Open(); // 核心SQL:数据库QTY = 原QTY - 修改后的数值 string updateQuery = "UPDATE 你的产品表名 SET QTY = QTY - @ModifiedQty WHERE Code = @ProductCode"; SqlCommand cmd = new SqlCommand(updateQuery, con); cmd.Parameters.AddWithValue("@ModifiedQty", modifiedQty); cmd.Parameters.AddWithValue("@ProductCode", productCode); int affectedRows = cmd.ExecuteNonQuery(); if (affectedRows > 0) { MessageBox.Show("更新成功!"); // 更新后重新查询,刷新DataGrid显示最新数据 txtCode_KeyDown(txtCode, new KeyEventArgs(Keyboard.PrimaryDevice, Keyboard.PrimaryDevice.ActiveSource, 0, Key.Enter)); } else { MessageBox.Show("未找到对应产品记录"); } } catch (Exception ex) { MessageBox.Show($"更新失败:{ex.Message}"); } } } else { MessageBox.Show("请先查询到产品数据再执行更新"); } }
四、几个关键注意事项
- 数据库连接字符串管理:建议把连接字符串放到
App.config里,方便后续修改,示例:
后台读取时用<configuration> <connectionStrings> <add name="ProductDB" connectionString="Data Source=你的SQL服务器地址;Initial Catalog=你的数据库名;Integrated Security=True;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>ConfigurationManager.ConnectionStrings["ProductDB"].ConnectionString(需要引用System.Configuration程序集) - 数据验证:可以在DataGrid的QTY列添加输入验证,比如限制只能输入正整数,避免出现负数或无效值
- 多记录处理:如果你的需求是支持批量修改多条记录,只需要遍历
dgProducts.Items里的每一行,逐个处理更新即可 - MVVM优化:如果项目规模较大,建议采用MVVM模式,用
ObservableCollection代替DataTable,实现INotifyPropertyChanged接口,让代码的可维护性更高
内容的提问来源于stack exchange,提问作者lex
相关产品推荐
相关产品推荐

