我有一个GetProduct方法,该方法应该在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(); } }
1 回答
- 1 回答
- 0 关注
- 155 浏览
添加回答
举报
0/150
提交
取消