【问题标题】:Information from arrays in c# using listbox使用列表框在 c# 中来自数组的信息
【发布时间】:2016-09-14 13:21:50
【问题描述】:

我正在使用列表框为班级项目创建一个小商店。 我有 3 个数组,项目(存储名称的字符串)、价格(存储价格的小数)、图片(存储项目的图像)。

http://prnt.sc/chrn6z

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

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

prices[lstCart.SelectedIndex]

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

【问题讨论】:

  • 购物车是另一个 ListBox 吗?如果是这样,您将存储什么,将项目名称作为字符串?
  • lhttp://hastebin.com/kenowocefe.pl @Keyur

标签: c# arrays listbox


【解决方案1】:

编辑

在这里更容易更改:

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。这有点混乱,但如果它有效,请告诉我。

【讨论】:

  • gyazo.com/13bca76ae71a3ac83830e62fce96f750 这就是它的工作原理,所以不确定如何,添加它的方式会有所帮助。
  • 编辑了答案以匹配您的场景。
  • 都没有用。首先,不返回任何信息,然后返回 NullReference @keyur
  • 然后在第一行string input之前添加if (lstCart.SelectedItem == null) { return; }。此外,如果在运行该代码之前从列表框中选择一个项目,SelectedItem 如何返回 null。它不寻常。
  • 一开始不能打电话给lstCart.Items.Remove(lstCart.SelectedItem);!在关闭函数之前调用它,否则 SelectedItem 显然为空。
【解决方案2】:

您可以做一些事情,例如找到您选择的产品的原始索引,然后将其用作索引以获得相应的价格。

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

【讨论】:

  • 字符串 selectedProduct = lstCart.SelectedItem.ToString();这会返回 NullReference?
  • lstCart 是您的购物车列表框的名称?
  • 是的。这是名字
  • 您是如何将商品添加到购物车的?
  • @lamelemon 非常明显的问题:lstCart.Items.Remove(lstCart.SelectedItem); 在函数的开头而不是结尾。否则我认为你的答案会奏效。
猜你喜欢
  • 2019-04-04
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2018-10-14
相关资源
最近更新 更多