【发布时间】: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