C# foreach 条件中的列表框项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15156215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:17:29  来源:igfitidea点击:

Listbox item in foreach Condition

c#winformslistbox

提问by Amrit Sharma

I like to get the string of the current item in foreach condition.

我喜欢在 foreach 条件下获取当前项目的字符串。

 public void checkStock()
 {
    foreach (var listBoxItem in listBox1.Items)
    {
        if (Convert.ToInt32(GetStock(listBox1.Items.ToString())) == 0)
        {
            MessageBox.Show("Item not in stock  ");
        }
    }
 }           

So that I can display the name of the item that is not in stock like "

这样我就可以显示没有库存的商品的名称,例如“

MessageBox.Show("{0}" +"not in stock" , listbox.items.ToString());

采纳答案by Jeff

    public void checkStock()
    {
        foreach (var listBoxItem in listBox1.Items)
        {
            // use the currently iterated list box item
            MessageBox.Show(string.Format("{0} is not in stock!",listBoxItem.ToString()));

        }
    }

I dont know how you are supposed to check if it really IS in stock though - this basically just iterates the collection, and prints out each item. You didn't specify how to check the stock.

我不知道你应该如何检查它是否真的有库存 - 这基本上只是迭代集合,并打印出每个项目。您没有指定如何检查库存。

回答by Sergio

This'l work as well:

这也可以:

MessageBox.Show("{0} not in stock", listBoxItem.ToString());

回答by CloudyMarble

Use the string.formatmethod with the foreach local variable listBoxItemwhich i guess should be used to check wether the item is in the stok too.

使用带有 foreach 局部变量的string.format方法listBoxItem,我想应该使用它来检查项目是否也在 stok 中。

public void checkStock()
 {
    foreach (var listBoxItem in listBox1.Items)
    {
        if (Convert.ToInt32(GetStock(listBoxItem.ToString())) == 0)
        {
            MessageBox.Show(string.Format("{0} is not in stock!",listBoxItem.ToString()));
        }
    }
 }        

回答by Debashish Tripathy

You can use listBoxItem local variable inside if clause.

您可以在 if 子句中使用 listBoxItem 局部变量。