Reputation: 75
I have to use a ListBox
for this.
I currently know how to remove from a ListBox
using this code:
private void removeButton_Click(object sender, EventArgs e)
{
REMOVE();
}
private void REMOVE()
{
int c = lstCart.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (lstCart.GetSelected(i))
{
lstCart.Items.RemoveAt(i);
}
}
}
But what I have found is that when I add another item, it clears the ListBox
and shows each item from the list, so it includes the 'removed' item because it wasn't removed from the list, only the ListBox
.
I'm thinking that what I need to do is remove the selected line from the List, then clear the ListBox
and repopulate it with the updated List data. But I'm struggling to find out how to do this.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
OrderItem currentItem = new OrderItem(txtItemName.Text,
Decimal.Parse(txtPrice.Text), (int)numQTY.Value);
myBasket.Add(currentItem);
lstCart.Items.Clear();
foreach (OrderItem i in myBasket)
{
lstCart.Items.Add(String.Format("{0,-40}
{1,-40} {2,-40} {3,-40}", i.ProductName,
i.Quantity.ToString(), i.LatestPrice.ToString(),
i.TotalOrder.ToString()));
}
txtItemTotal.Text = "£" + myBasket.BasketTotal.ToString();
txtItemCount.Text = myBasket.Count.ToString();
}
private void removeButton_Click(object sender, EventArgs e)
{
int c = lstCart.Items.Count - 1;
for (int i = c; i >= 0; i--)
{
if (lstCart.GetSelected(i))
{
lstCart.Items.RemoveAt(i);
}
}
????
}
}
ShoppingBasket class:
public class ShoppingBasket
{
public ShoppingBasket()
{
}
public new void Add(OrderItem i)
{
base.Add(i);
calcBasketTotal();
}
private void calcBasketTotal()
{
BasketTotal = 0.0M;
foreach (OrderItem i in this)
{
BasketTotal += i.TotalOrder;
}
}
public new void Remove(OrderItem i)
{
????
}
}
OrderItem class:
public class OrderItem
{
public OrderItem(string productName,
decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
}
Upvotes: 1
Views: 511
Reputation: 12956
Your add method calls Add(
) on a base class. Do you have a remove on your base class? If so, use that. Otherwise change your ShoppingBasket
class to be:
The Orders
list stores your OrderItems
. Add and Remove from this list.
public class ShoppingBasket
{
public List<OrderItem> Orders { get; set; }
public ShoppingBasket()
{
Orders = new List<OrderItem>();
}
public void Add(OrderItem orderItem)
{
Orders.Add(orderItem);
}
public void Remove(OrderItem orderItem)
{
Orders.Remove(orderItem);
}
}
Usage:
var basket = new ShoppingBasket();
basket.Add( new OrderItem { OrderItemId = 1, ... } );
// Remove an OrderItem
basket.Remove( new OrderItem { OrderItemId = 1 } );
Upvotes: 1