c# - InvalidCastException : Unable to cast object of type 'System.Decimal' to type 'System.String'

标签 c# asp.net data-binding

我试图从表格中获取销售价格并将其放入文本框中。在我的表上,销售价格是一个 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/

相关文章:

c# - 在 XML 解析器中处理非标准引号的最佳方式

c# - 这会删除所有可能的脚本标签吗?

javascript - Asp.net core mvc 将 int 数组发送到 Controller

c# - 如何清除asp mvc中指定 Controller 中的缓存?

asp.net - 在 IE 6 中调整 Div 大小

javascript - 为什么会出现 "Cannot read property ' click' of null 错误

DataTemplate 中的 WPF 命令绑定(bind)

android - recyclerview适配器android中的数据绑定(bind)?

asp.net - IE 和 ASP.NET 的 IPv6 范围 ID 问题

.net - 如何绑定(bind)到列表中的最后一项?