如何从列表框中取出项目,在同一位置的另一个列表框中取出另一个项目

时间:2015-12-01 17:07:57

标签: c# visual-studio listbox listboxitems

我正在尝试创建一个方法,该方法将获取一个列表框的值,并且也将从同一索引处的另一个列表框中取出。我只是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);
                }

1 个答案:

答案 0 :(得分: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);