Reputation: 91
I'm creating a list with 5 items. 4 of the items are manually hard-coded, but the 5th (int Quantity) is an int value that needs to be entered via textbox. I'm struggling with how to enter the 5th item. Any help would be appreciated.
Class:
public class Product_Class
{
public string ProdName { get; set; }
public decimal ProdPrice { get; set; }
public string ItemNumber { get; set; }
public string UPC { get; set; }
public int Quantity { get; set; }
}
Product Page:
public Product_Class(string ProdName, decimal ProdPrice, string ItemNumber,
string UPC, int Quantity)
{
this.ProdName = ProdName;
this.ProdPrice = ProdPrice;
this.ItemNumber = ItemNumber;
this.UPC = UPC;
this.Quantity = Quantity;
}
public partial class Products_Accents_Mini : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
if(Session["ObjList"] == null)
{
List<Product_Class> objList = new List<Product_Class>();
Session["ObjList"] = objList;
}
Product_Class prod1 = new Product_Class("Watercolor Apples Mini Accents",
5.99M, "5635", "88231956358");
List<Product_Class> objList2 = (List<Product_Class>)Session["ObjList"];
objList2.Add(prod1);
Session["ObjList"] = objList2;
}
protected void Button4_Click(object sender, EventArgs e)
{
Response.Redirect("ShoppingCart.aspx");
}
}
Upvotes: 0
Views: 1455
Reputation: 182
Didn't see accepted answer, but alternate method to arrive at the same destination!
You can keep your constructor if you'd like. When you create a new Product Class object, just set the initial quantity as zero, then set it as the textbox value afterwards.
//Create your new object with a default value for quantity
Product_Class prod1 = new Product_Class("Watercolor Apples Mini Accents", 5.99M, "5635", "88231956358", 0);
//Get and Set your quantity value
int quantity = Convert.ToInt32(tbQuantity.Text);
prod1.Quantity = quantity;
Upvotes: 1
Reputation: 5068
Looks like you are trying create a constructor in the product page, but I think you should be doing it in the class itself.
Another approach would be to remove your constructor (use the default constructor, and getters and setters) and set the values manually.
We used to have to manually set every value of an object (this.ProdName = ProdName;
) in setters, but C# was updated so we only have to do public string ProdName { get; set; }
. But they are the same (they work the same in the background).
In the button click event:
if (Session["ObjList"] == null)
{
List<Product_Class> objList = new List<Product_Class>();
Session["ObjList"] = objList;
}
Product_Class prod1 = new Product_Class();
prod1.ProdName = "Watercolor Apples Mini Accents";
prod1.ProdPrice = 5.99M;
prod1.ItemNumber = "5635";
prod1.UPC = "88231956358";
prod1.Quantity= int.Parse(txt.Text);
List<Product_Class> objList2 = (List<Product_Class>)Session["ObjList"];
objList2.Add(prod1);
Upvotes: 1