c#中使用列表框的数组信息

本文关键字:数组 信息 列表 | 更新日期: 2023-09-27 18:06:49

我正在使用列表框为一个类项目创建一个小商店。我有3个数组,items(存储名称的字符串),prices(存储价格的十进制),pics(存储商品的图像)。

http://prnt.sc/chrn6z

我有一切工作,除了从购物车按钮删除项目。当它从右列表框中删除一个项目时,它需要从totalprice变量中减去该列表框中所选项目的价格。

我的问题是,我不知道如何获得购物车(右列表框)中商品的价格数组小数。我试过了:

prices[lstCart.SelectedIndex]

我试过了,但是它给了我一个IndexOutOfRangeException。

c#中使用列表框的数组信息

编辑

在这里更容易修改:

private void btnRemove_Click(object sender, EventArgs e)
{
    string selectedProduct = lstCart.SelectedItem.ToString();
    int selectedProductIndex = Array.FindIndex(items, row => selectedProduct.Contains(row));
    if (selectedProductIndex == -1) return;
    decimal selectedProductPrice = prices[selectedProductIndex];
    totalPrice = totalPrice - selectedProductPrice;
    MessageBox.Show(totalPrice.ToString());
    lstCart.Items.Remove(lstCart.SelectedItem);
}

因为你的selectedProduct是一个由item和price组成的字符串,它应该满足Contains。这是一个有点混乱的hack,但如果它工作,请告诉我。

您可以做一些事情,比如查找所选产品的原始索引,然后使用它作为索引来获得相应的价格。

string selectedProduct = lstCart.SelectedItem.ToString();
int selectedProductIndex = Array.IndexOf(products, selectedProduct);
double selectedProductPrice = prices[selectedProductIndex];
totalPrice = totalPrice - selectedProductPrice;