我必须为此使用 a ListBox
。
我目前知道如何ListBox
使用以下代码从 a 中删除:
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);
}
}
}
但是我发现,当我添加另一个项目时,它会清除ListBox
并显示列表中的每个项目,因此它包含“已删除”项目,因为它没有从列表中删除,只有ListBox
. 我在想我需要做的是从列表中删除选定的行,然后清除ListBox
并使用更新的列表数据重新填充它。但我正在努力寻找如何做到这一点。
表格1:
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);
}
}
????
}
}
购物篮类:
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)
{
????
}
}
订单项类:
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; }
}