我的代码中存在一些问题(在我们的sql数据库UnitPrice
和TotalPrice
数据类型decimal
中,当我想添加数据时出现此错误
“将数据类型varchar转换为数字错误
我的代码:
#region EDIT RECORD
private bool EditRecord()
{
DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
if (row == null) return false;
PopupChillers frm = new PopupChillers();
frm.InitData(this.FindForm(), gridControl3, gridView1, row);
bool ret = frm.ShowDialog() == DialogResult.OK;
if (ret)
{
row.ItemArray = frm.Row.ItemArray;
string DegiskenId;
DegiskenId = row[0].ToString();
#region Kaydet guncelle hata kontrolu
try
{
#region Guncelle
if (KayitSekli == "GUNCELLE")
{
string gsorgu = "UPDATE OrnekTbl SET ProjectName=@ProjectName,UnitPrice=@UnitPrice,TotalPrice=@TotalPrice WHERE ProjectName='" + DegiskenId + "'";
objSqlDataAdapter.UpdateCommand = new SqlCommand(gsorgu, objSqlConnection);
objSqlDataAdapter.UpdateCommand.Parameters.Add("@ProjectName", SqlDbType.VarChar).Value = row[0].ToString();
objSqlDataAdapter.UpdateCommand.Parameters.Add("@UnitPrice", SqlDbType.VarChar).Value = row[1].ToString();
objSqlDataAdapter.UpdateCommand.Parameters.Add("@TotalPrice", SqlDbType.VarChar).Value = row[2].ToString();
{
objSqlConnection.Open();
objSqlDataAdapter.UpdateCommand.ExecuteNonQuery();
}
objSqlConnection.Close();
}
#endregion
#region Kaydet
if (KayitSekli == "KAYDET")
{
string ksorgu = "INSERT INTO OrnekTBL (ProjectName,UnitPrice,TotalPrice) VALUES (@ProjectName,@UnitPrice,@TotalPrice)";
objSqlDataAdapter.InsertCommand = new SqlCommand(ksorgu, objSqlConnection);
objSqlDataAdapter.InsertCommand.Parameters.Add("@ProjectName", SqlDbType.VarChar).Value = row[0].ToString();
objSqlDataAdapter.InsertCommand.Parameters.Add("@UnitPrice", SqlDbType.VarChar).Value = row[1].ToString();
objSqlDataAdapter.InsertCommand.Parameters.Add("@TotalPrice", SqlDbType.VarChar).Value = row[2].ToString();
if (objSqlConnection.State == ConnectionState.Closed)
{
objSqlConnection.Open();
objSqlDataAdapter.InsertCommand.ExecuteNonQuery();
}
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
objSqlConnection.Close();
}
#endregion
row.EndEdit();
}
return ret;
}
#endregion
答案 0 :(得分:0)
错误消息似乎很清楚。看看你的参数:
objSqlDataAdapter.UpdateCommand.Parameters.Add("@UnitPrice", SqlDbType.VarChar).Value = row[1].ToString();
objSqlDataAdapter.UpdateCommand.Parameters.Add("@TotalPrice", SqlDbType.VarChar).Value = row[2].ToString();
您明确将其声明为SqlDbType.VarChar
。但是,字段名称表明它们是数值。 (Money?Decimal?)参数需要匹配列的数据类型。也许是这样的:
decimal unitPrice = 0;
if (!decimal.TryParse(row[1].ToString(), out unitPrice))
{
// TODO: Handle the error if it's not a valid decimal
}
objSqlDataAdapter.UpdateCommand.Parameters.Add("@UnitPrice", SqlDbType.Decimal).Value = unitPrice;