Amrit Sharma
Amrit Sharma

Reputation: 1916

Listbox item in foreach Condition

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

 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());

Upvotes: 1

Views: 66012

Answers (4)

CloudyMarble
CloudyMarble

Reputation: 37566

Use the string.format method with the foreach local variable listBoxItem which i guess should be used to check wether the item is in the stok too.

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()));
        }
    }
 }        

Upvotes: 0

Sergio
Sergio

Reputation: 6948

This'l work as well:

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

Upvotes: 0

Debashish Tripathy
Debashish Tripathy

Reputation: 67

You can use listBoxItem local variable inside if clause.

Upvotes: 0

Jeff
Jeff

Reputation: 12183

    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.

Upvotes: 4

Related Questions