You need to understand
scope
- have a read of this MSDN article
Variable and Method Scope in Microsoft .NET[
^]
Looking at the code from your comment, you are declaring a second
Product
object for no good reason.
product
where it is declared is fine as it is available everywhere you want to reference it. I think you are getting confused between
declaring a variable and creating
a new instance of it
Note that your code will not work because you have misspelled "SELECT" in your
query
. There are unneccesary braces added as well.
Something similar to this should be fine (untested!). Please take note of the comments I have added.
public static Product ReadProductById(int prodId)
{
Product product = null;
using(SqlConnection connection = ConnectionString.GetSqlConnection())
{
string query = "SELECT * FROM Products WHERE ProductId = @pid";
using(SqlCommand cmdRead = new SqlCommand(query, connection))
{
cmdRead.Parameters.AddWithValue("@pid", prodId);
using(SqlDataReader reader = cmdRead.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
product = new Product()
ProductId = Convert.ToInt32(reader["ProductId"]),
ProductName = reader["ProductName"].ToString(),
ProductPrice = Convert.ToDecimal(reader["ProductPrice"]),
ProductListedDate = Convert.ToDateTime(reader["ProductListedDate"]),
ProductTax = Convert.ToDecimal(reader["ProductTax"]),
UserId = Convert.ToInt32(reader["UserId"]),
ProductQuantity = Convert.ToInt32(reader["ProductQuantity"]),
ProductTotal = Convert.ToDecimal(reader["ProductTotal"]),
ProductPurchasedDate = Convert.ToDateTime(reader["ProductPurchasedDate"]),
ReceiptId = Convert.ToInt32(reader["ReceiptId"])
}
}
}
}
}
return product;
}