【问题标题】:How to take an item out of a list box and another item in a different list box in the same position如何从列表框中取出一个项目,并在同一位置的不同列表框中取出另一个项目
【发布时间】:2015-12-01 17:07:56
【问题描述】:

我正在尝试创建一种方法,该方法将采用一个列表框的值,并且还将从同一索引处的另一个列表框中取出。我只是 C# 的初学者,这就是我遇到这个问题的原因。在此先感谢您的帮助

if (lstCheckoutProduct.)
                {
                    lstCheckoutProduct.Items.Remove(lstCheckoutProduct.SelectedItem);
                    int productIndex = lstCheckoutProduct.Items.IndexOf(lstCheckoutProduct.SelectedIndex);
                    lstCheckoutPrice.Items.Remove(productIndex);
                }
                else
                {
                    lstCheckoutPrice.Items.Remove(lstCheckoutPrice.SelectedItem);
                    int priceIndex = lstCheckoutPrice.Items.IndexOf(lstCheckoutPrice.SelectedIndex);
                    lstCheckoutPrice.Items.Remove(priceIndex);
                }

【问题讨论】:

  • 您的第一个 if 语句是否应该检查是否有选定的项目?它只是以一个点结束
  • lstCheckoutPrice.Items.IndexOf(lstCheckoutPrice.SelectedIndex) 为什么?
  • 在你的 else 我认为你应该从 lstCheckoutProduct.items 而不是 lstCheckoutPrice.items 中删除
  • 我使用了选定的索引,因为我认为如果我获得产品的位置,那么价格将在不同的列表框上的相同索引中,因此我可以找到它
  • @M.Walker,您无需同时尝试IndexOfSelectedIndexSelectedIndex 就够了。

标签: c# visual-studio listbox listboxitems


【解决方案1】:

您需要在删除项目之前获取 SelectedIndex。另外我假设你的第一行应该检查列表框是否有焦点

如果要删除特定索引处的项目,则需要使用RemoveAt 而不是Remove

if (lstCheckoutProduct.IsFocused)
{
  int productIndex = lstCheckoutProduct.SelectedIndex;
  lstCheckoutProduct.Items.Remove(lstCheckoutProduct.SelectedItem);
  lstCheckoutPrice.Items.RemoveAt(productIndex);
}
else
{
  int priceIndex = lstCheckoutPrice.SelectedIndex;
  lstCheckoutPrice.Items.Remove(lstCheckoutPrice.SelectedItem);
  lstCheckoutProduct.Items.RemoveAt(priceIndex);
}

编辑:第一行只是您在问题中遗漏的猜测。注意IsFocused 将是false,如果用户点击了一个“删除”按钮(从而聚焦按钮而不是列表框)来调用这个方法。

编辑:您可以将代码简化为:

int index = lstCheckoutProduct.IsFocused ? lstCheckoutProduct.SelectedIndex : lstCheckoutPrice.SelectedIndex;
lstCheckoutProduct.Items.RemoveAt(index);
lstCheckoutPrice.Items.RemoveAt(index);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多