sean

sean

  • NA
  • 3
  • 0

Manipulating a ListBox

Mar 28 2008 7:16 PM
have a form that utilizes two ListBox elements. On the left is a list of groceries and their price. On the right is the current groceries in the "shopping cart" with their quantity and total cost. I should select an inventory item then press a button to add it to the shopping cart. The right side now reads: 1 bread @2.99 per unit 2.99. If I press the button again, it should read: 2 bread @2.99 per unit 5.98. Here is my code so far:

Grocery Item class











namespace Project2
{
class GroceryItem
{
private String name;
private double price;
private double quantity;

public GroceryItem(String newName, double newPrice)
{
this.name = newName;
this.price = newPrice;
this.quantity = 0;
}

public void IncreaseQuantity()
{
quantity = quantity + 1;
}

public void DecreaseQuantity()
{
quantity = quantity - 1;
}

public double GetQuantity()
{
return this.quantity;
}

public double GetCost()
{
quantity = quantity * price;
return this.quantity;
}

public override string ToString()
{


if (this.quantity == 0)
{
return this.name + " " + this.price.ToString();

}

else if (this.quantity > 0)
{
return this.quantity.ToString() + " " + this.name + "@" + this.price.ToString() + " " + "per unit" + " " + this.GetCost();


}

return base.ToString();
}














Here is the code that actually adds the currently selected item to the shopping cart. If the quantity is 1, you simply add it to the shopping cart. If not, more work is involved. My instructions actually read,

"If the quantity of the current item is now one, then just add current to the grocery cart list box. Otherwise, you will actually need to loop through the items in the grocery Items list, and find the one that matches current. If it matches, then you have to assign current to the list at that location."










private void button1_Click(object sender, EventArgs e)
{
int i = 0;
GroceryItem current = (GroceryItem)InventoryBox.SelectedItem;
current.IncreaseQuantity();

if (current.GetQuantity() == 1)
{
GroceryList.Items.Add(current);
}
else
{
foreach (object pres in GroceryList.Items)
{
if (current == pres)
{

}
}
}

}