如何使用DataGridViewImageColumn编辑指定列并实现商品库存与价格更新
如何使用DataGridViewImageColumn编辑指定列?
需求说明
你想用DataGridViewImageColumn实现两个核心操作:
- 添加商品销售数量时,同步提高商品价格
- 售出商品时,同时减少DataGridView对应列的库存数量,并更新数据库中的库存数据,确保销售数量和库存变化同步
实现步骤
绑定图片列的点击事件
给DataGridView的CellContentClick事件绑定处理方法,先判断点击的列是否是目标DataGridViewImageColumn,确认后再执行业务逻辑。读取当前行数据并计算新值
从点击的行中获取当前商品的价格、库存和ID,根据实际销售数量(建议从输入框读取)计算新价格和新库存,同时要校验库存是否足够支撑本次销售。更新DataGridView显示
将计算后的新价格、新库存赋值回对应的单元格,让界面实时同步数据变化。安全更新数据库
使用参数化查询更新数据库,避免直接拼接SQL语句带来的注入风险,同时确保数据库与表格数据一致。
优化后的代码实现
原代码存在SQL注入风险,且库存减少为固定值(减1),无法适配实际销售数量,以下是改进后的版本:
// 从输入框获取销售数量,比如txtSaleQuantity是你的销售数量输入控件 int saleQuantity; if (!int.TryParse(txtSaleQuantity.Text, out saleQuantity) || saleQuantity <= 0) { MessageBox.Show("请输入有效的销售数量"); return; } // 获取当前点击行的数据 DataGridViewRow currentRow = dgvProduct.Rows[e.RowIndex]; int productId = Convert.ToInt32(currentRow.Cells[0].Value); double currentPrice = Convert.ToDouble(currentRow.Cells[4].Value); int currentQuantity = Convert.ToInt32(currentRow.Cells[3].Value); // 校验库存是否充足 if (currentQuantity < saleQuantity) { MessageBox.Show("库存不足,无法完成本次销售"); return; } // 计算新值(价格提高比例可根据你的需求调整,这里示例为提高10%) double newPrice = currentPrice * 1.1; int newQuantity = currentQuantity - saleQuantity; // 更新DataGridView的显示 currentRow.Cells[4].Value = newPrice; currentRow.Cells[3].Value = newQuantity; // 使用参数化查询更新数据库,避免SQL注入 string query = "UPDATE tbProduct SET Quantity = @NewQuantity, Price = @NewPrice WHERE Pid = @ProductId"; using (SqlCommand cmd = new SqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("@NewQuantity", newQuantity); cmd.Parameters.AddWithValue("@NewPrice", newPrice); cmd.Parameters.AddWithValue("@ProductId", productId); dbcon.Open(); cmd.ExecuteNonQuery(); dbcon.Close(); }
关键注意事项
- 事件绑定:记得在窗体初始化时绑定事件,比如在
Form_Load方法中添加:dgvProduct.CellContentClick += dgvProduct_CellContentClick; - 数据校验:用
TryParse做类型转换,避免出现类型异常;销售前一定要检查库存是否足够,防止负库存 - SQL安全:绝对不要直接拼接SQL语句,参数化查询是避免注入的基础操作
- 连接管理:用
using语句管理数据库连接,能自动释放资源,避免连接泄漏
内容的提问来源于stack exchange,提问作者Jerecho Rey Inatilleza
相关产品推荐
相关产品推荐

