DataGridView更新数据库decimal列时出现nvarchar转numeric错误
解决DataGridView更新decimal列时的类型转换错误
问题原因
你遇到的“将数据类型nvarchar转换为numeric时出错”,根源是参数类型不匹配:即使你把输入解析成了decimal,又转成string传给SQL参数,SQL Server会把这个参数当作nvarchar类型处理,而数据库列是decimal/numeric类型,转换时就会触发错误。
解决方案
不要将decimal值转为string传递,直接保留decimal类型的参数值,让SQL参数类型和数据库列类型严格匹配。修改思路:
- 用
object类型存储单元格新值,根据列类型存储对应的数据类型(string或decimal) - 解析decimal后直接保留decimal值,不再转成string
- 传参时直接传递对应类型的变量,让ADO.NET自动匹配SQL参数类型
修改后的代码
private void UpdateDataInTable(string tableName, int rowIndex, int columnIndex) { try { int id = Convert.ToInt32(dataGridView1.Rows[rowIndex].Cells["Medicineid"].Value); object newValue = null; DataGridViewColumn col = dataGridView1.Columns[columnIndex]; DataGridViewCell cell = dataGridView1.Rows[rowIndex].Cells[columnIndex]; if (col.ValueType == typeof(decimal)) { decimal decimalValue; if (decimal.TryParse(cell.Value?.ToString(), out decimalValue)) { newValue = decimalValue; } else { MessageBox.Show("数字格式错误。"); return; } } else { // 处理字符串等其他类型,兼容空值 newValue = cell.Value?.ToString() ?? string.Empty; } string query = $"UPDATE {tableName} SET {col.Name} = @newValue WHERE Medicineid = @id"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@newValue", newValue); command.Parameters.AddWithValue("@id", id); command.ExecuteNonQuery(); } } } catch (Exception ex) { MessageBox.Show("更新数据时出错: " + ex.Message); } }
额外优化建议
- 为了更严谨,可显式指定SQL参数类型,避免
AddWithValue的类型推断问题,比如decimal列:command.Parameters.Add("@newValue", SqlDbType.Decimal).Value = decimalValue; - 增加单元格空值处理,避免
ToString()触发空引用异常
内容的提问来源于stack exchange,提问作者skotseierlFF
相关产品推荐
相关产品推荐

