我有一個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 回答
- 0 關注
- 168 瀏覽
添加回答
舉報
0/150
提交
取消