想要列表框中所选项目的索引值



如何检索苹果的值?

http://oi59.tinypic.com/2mwbe61.jpg

我知道第一行代码不正确,但这正是我希望我的删除按钮所做的:

private void btnRemove_Click(object sender, EventArgs e)
{
   //string productName = lbxProducts.SelectedItem.Index[0].GetValue;
   //product.RemoveProduct(productName);
   //RenderBasket();
}

列表框中项目的第一个值是产品名称(这就是我想要第一个元素的原因)。

我的RemoveProduct方法:

    public void RemoveProduct(string productToRemove, int quantity)
    {
        try
        {
            foreach (OrderItem order in OrderItems)
            {
                if (order.ProductName == productToRemove)
                {
                    order.RemoveItems(quantity);
                    if (order.Quantity == 0) { OrderItems.Remove(order); }
                }
            }
        }

这就是我的列表框(lbxProducts)的填充方式:

private void RenderBasket()
    {
        lbxProducts.Items.Clear();
        txtNumberOfProducts.Text = string.Format("{0}", product.NumberOfProducts);
        txtNumberOfItems.Text = string.Format("{0}", product.NumberOfItems);
        txtTotal.Text = string.Format("{0:C2}", product.BasketTotal);
        Controls.Add(lbxProducts);
        lbxProducts.BeginUpdate();
        foreach (OrderItem item in product.OrderItems)
        {
            lbxProducts.Items.Add(string.Format("{0,-15} t {1,4} t {2,10:C2} t {3,10:C2}",
                item.ProductName, item.Quantity, item.LatestPrice, item.TotalOrder));
        }
        lbxProducts.EndUpdate();
    }

我是编程新手,所以我仍然不确定我能做什么,不能做什么,但我在这个小阶段已经太久了。非常感谢这里的帮助。

如果你只想得到Listbox索引的名称,那么你可以这样做,

listBox1.SelectedItem.ToString();

如果你想获得列表中项目的索引

//note that the index is 0 based
listBox1.SelectedIndex;

试试这个:

string value = listbox.Items[listbox.SelectedIndex].ToString();

您可以使用:

lbxProducts.SelectedItem.ToString();

lbxProducts.SelectedValue.ToString();

以获取所选项目的值。

如果你有多个选择的项目,你可以使用

if (lbxProducts.SelectedIndex != -1)
    lbxProducts.SelectedItems[lbxProducts.SelectedIndex].ToString();

您可以执行以下操作:

for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
    string removelistitem = "WHATEVER YOU WANT TO REMOVE";
    if (listBox1.Items[n].ToString().Contains(removelistitem))
    {
        listBox1.Items.RemoveAt(n);
    }
}

最新更新