我试图从表格中获取销售价格并将其放入文本框中。在我的表上,销售价格是一个 Decimal 变量,当然文本框是字符串。当我运行它时,有一个异常在我的数据访问层中停止它。
这是一些代码:
textSellPrice.Text = DAL.Util.getSellPrice(listItemsPricing.SelectedValue.ToString());
public static String getSellPrice(string item)
{
string sql = "SELECT Price FROM Item it INNER JOIN Customers cu
ON it.SalesRep = Cu.SalesRep WHERE CustomerID='"
+ HttpContext.Current.Session["SelectedCustomer"] +
"' AND ProductID='" + item + "'";
string dt = AdoUtil.GetDataColumn(sql);
return dt;
}
public static string GetDataColumn(string sqlQuery)
{
string result = String.Empty;
try
{
SqlCommand cmd = new SqlCommand(sqlQuery, GetACESConn());
if (cmd.Connection.State != ConnectionState.Open)
cmd.Connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
while (reader.Read())
{
result = reader.GetString(0);
}
if (cmd.Connection.State != ConnectionState.Closed)
cmd.Connection.Close();
return result;
}
catch (Exception ex)
{
return result;
}
}
那么有什么完全明显的东西是我遗漏的吗?
感谢您对此有任何有用的见解,如果可以使用任何其他代码,我可以提供。谢谢
最佳答案
您正在选择一个价格,大概是一个小数。所以不要调用 reader.GetString(0)
- 调用 reader.GetDecimal(0)
并将结果存储在 decimal
变量中。如果您真的想将所有内容都转换成字符串,只需调用 GetValue(0).ToString()
。
当你在那里时,请解决这个问题:
string sql = "SELECT Price FROM Item it INNER JOIN Customers cu ON it.SalesRep = Cu.SalesRep WHERE CustomerID='" + HttpContext.Current.Session["SelectedCustomer"] +
"' AND ProductID='" + item + "'";
这只是乞求SQL Injection Attack . 不要像这样将值直接放入 SQL。相反,使用参数化 SQL 并指定这些参数的值。参见 SqlCommand.Parameters
举个例子。
接下来,不要捕获Exception
,并且当抛出异常时不要返回值,就好像什么都没发生一样......你会无缘无故地掩盖错误。
关于c# - InvalidCastException : Unable to cast object of type 'System.Decimal' to type 'System.String' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216518/