从MessageBox中的数据库中检索信息IndexOutOfBoundsException异常

时间:2018-05-01 18:47:54

标签: c# sql ado.net indexoutofboundsexception

我有一个GetProduct方法,它应该在MessageBox中返回产品代码,描述和价格。目前,我只能在实际找到与代码匹配的产品时,在“IndexOutOfBoundsException”框中显示带有标题的“价格”一词。如果没有,则表明找不到它。

以下是代码:

        public static Product GetProduct(string code)
    {
        SqlConnection connection = Connection.GetConnection();

        string select = @"SELECT ProductCode, Description, UnitPrice FROM Products WHERE ProductCode = @ProductCode";

        SqlCommand selectCommand = new SqlCommand(select, connection);


        SqlParameter pCode = new SqlParameter();
        pCode.ParameterName = "@ProductCode";
        pCode.Value = product.Code;
        SqlParameter pDesc = new SqlParameter();
        pDesc.ParameterName = "@Description";
        pDesc.Value = product.Description;
        SqlParameter pPrice = new SqlParameter();
        pPrice.ParameterName = "@UnitPrice";
        pPrice.Value = product.Price;

        selectCommand.Parameters.AddWithValue("@ProductCode", code);

        try
        {
            connection.Open();

            SqlDataReader prodReader = selectCommand.ExecuteReader(CommandBehavior.SingleRow);

            if (prodReader.Read())
            {
                product.Code = prodReader["ProductCode"].ToString(); ;
                product.Description = prodReader["Description"].ToString();
                product.Price = ((decimal)prodReader["Price"]);

                return product;
            }
            else
            {
                return null;
            }
        }
        catch (SqlException ex)
        {
            throw ex;
        }
        finally
        {
            connection.Close();
        }

    }

1 个答案:

答案 0 :(得分:0)

您有一个名为 UnitPrice 的字段,而使用的读者字符串索引器名为 Price 。这会产生 IndexOutOfRangeException 虽然这是一个常见的错字,但有趣的是要知道为什么会发生这种情况。

数据阅读器的字符串索引器在内部包含此代码

override public object this[string name] {
    get {
        return GetValue(GetOrdinal(name));
    }
}

正如您所看到的,它使用GetOrdinal公共方法从其名称中检索字段的索引。但是,如果找不到传递的名称,则对GetOrdinal的调用返回-1,当然这不是从0到FieldCount的基础字段数组的有效索引 - 1