从 MessageBox 中的数据库中检索信息 |索引越界异常

Retrieve information from database in a MessageBox | IndexOutOfBoundsException

我有一个 GetProduct 方法,它应该 return MessageBox 中的产品代码、描述和价格。目前,当它实际找到与代码匹配的产品时,我只能在框 "IndexOutOfBoundsException" 上显示带有标题的单词 "Price"。如果没有,则显示未找到。

代码如下:

        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();
        }

    }

您有一个名为 UnitPrice 的字段,而 reader 使用的字符串索引器名为 Price。这会产生 IndexOutOfRangeException.
虽然这是一个常见的错字,但很有趣的是知道为什么会这样。

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

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

如您所见,它使用 GetOrdinal public method to retrieve the index of the field from its name. However, if the name passed is not found the call to GetOrdinal returns -1 and of course this is not a valid index on the underlying fields array going from 0 to FieldCount - 1