我想问你如何在更新表或将数据插入表之前、用户插入行之后或从 dataGridView 更新行之后将字符串转换为小数。
比如我把一个十进制值2.2
放到price列,然后我把它保存到数据库,然后我刷新表,这个值是2
,而不是 2.2
,或者添加 2.8
,然后表格显示我们是 3
,而不是 2.8
.
在我的例子中,我希望价格列是小数,我按照下面的方式进行,但它不起作用,请帮助,谢谢。
在 form1.css 中:
..............
//after a user click the save button
private void btnSave_Click(object sender, EventArgs e)
{
Infor.UpdateDataSet((DataSet)dataGridView1.DataSource);
}
.........
Infor.css
pInsert[3] = new SqlParameter("@p4", SqlDbType.Decimal, 40,
"price");
pUpdate[2] = new SqlParameter("@p4", SqlDbType.Decimal, 40,
"price");
…………
public static void UpdateDataSet(DataSet ds)
{
SqlConnection cnn = new SqlConnection(strConn);
string sqlInsert, sqlUpdate, sqlDelete;
sqlInsert = "insert into customers(customerid,companyname,
contactname,price) values(@p1,@p2,@p3,@p4)";
sqlUpdate = "update customers set companyname=@p2,
contactname=@p3,price=@p4 where customerid=@p1";
sqlDelete = "delete from customers where customerid=@p1";
SqlParameter[] pInsert = new SqlParameter[4];
SqlParameter[] pUpdate = new SqlParameter[4];
SqlParameter[] pDelete = new SqlParameter[1];
pInsert[0] = new SqlParameter("@p1", SqlDbType.VarChar, 5,
"CustomerID");
pInsert[1] = new SqlParameter("@p2", SqlDbType.VarChar, 40,
"CompanyName");
pInsert[2] = new SqlParameter("@p3", SqlDbType.VarChar, 40,
"ContactName");
pInsert[3] = new SqlParameter("@p4", SqlDbType.Decimal, 40,
"price");
pUpdate[0] = new SqlParameter("@p2", SqlDbType.VarChar, 40,
"CompanyName");
pUpdate[1] = new SqlParameter("@p3", SqlDbType.VarChar, 40,
"ContactName");
pUpdate[2] = new SqlParameter("@p4", SqlDbType.Decimal, 40,
"price");
pUpdate[3] = new SqlParameter("@p1", SqlDbType.VarChar, 5,
"CustomerID");
pDelete[0] = new SqlParameter("@p1", SqlDbType.VarChar, 5,
"CustomerID");
SqlCommand cmdInsert = new SqlCommand(sqlInsert,cnn);
SqlCommand cmdUpdate = new SqlCommand(sqlUpdate,cnn);
SqlCommand cmdDelete = new SqlCommand(sqlDelete,cnn);
cmdInsert.Parameters.AddRange(pInsert);
cmdUpdate.Parameters.AddRange(pUpdate);
cmdDelete.Parameters.AddRange(pDelete);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = cmdInsert;
da.UpdateCommand = cmdUpdate;
da.DeleteCommand = cmdDelete;
da.Update(ds, "customers");
ds.AcceptChanges();
}
最佳答案
小数有两个因素,小数位和精度。
精度是数字可以包含的位数。
小数位数是小数位数。
例子
- 1111.111(精度:7,小数位数 3)
- 11.11111(精度:7,小数位数 5)
您在创建参数 时没有表示比例,只有精度(编辑:您实际上是在构造函数中以字节为单位指定大小,而不是精度)。您需要明确设置 Precision 和 Scale 属性以获得您想要的结果。
例子
摘自 http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.scale.aspx .
SqlParameter parameter = new SqlParameter("Price", SqlDbType.Decimal);
parameter.Value = 3.1416;
parameter.Precision = 8;
parameter.Scale = 4;
来自上述来源的相关注释:
Data may be truncated if the Scale property is not explicitly specified and the data on the server does not fit in scale 0 (the default).
同样适用于表中的列定义,也必须指定精度和小数位数,当然要匹配。 (添加了来自@OlivierJacot-Descombes 的评论)
关于c# - 在更新表或将数据插入表之前将字符串转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089262/