I have a GetProduct method that is supposed to return the product code, description, and price in a MessageBox. Currently, I am only able to display the word "Price" with a title on the box "IndexOutOfBoundsException" when it actually finds a product matching the code. If not, it displays that it is not found.
Here is the code:
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();
}
}