【问题标题】:Retrieve information from database in a MessageBox | IndexOutOfBoundsException [duplicate]从 MessageBox 中的数据库中检索信息 | IndexOutOfBoundsException [重复]
【发布时间】:2018-10-11 19:45:18
【问题描述】:

我有一个 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();
        }

    }

【问题讨论】:

  • 该字段名为 UnitPrice,您尝试从名为 Price 的索引器中读取,是拼写错误还是您真正的问题?
  • @Steve 我敢打赌这正是 OP的问题
  • 谢谢@Steve,我犯了愚蠢的错误。现在尝试找出下一步。

标签: c# sql ado.net indexoutofboundsexception


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    相关资源
    最近更新 更多