2013-03-01 16 views
0

我喜歡在foreach條件下獲取當前項目的字符串。在foreach中的列表框項目條件

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

所以,我可以顯示該項目的名稱,是不是在庫存中有象「

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

你面臨哪個問題? – CloudyMarble 2013-03-01 11:06:38

+0

您的意思是:MessageBox.Show(「{0}」+「not stock」,listBoxItem.ToString()); – CloudyMarble 2013-03-01 11:08:39

+0

對不起,我很困惑 – 2013-03-01 11:08:57

回答

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

     } 
    } 

我不知道你應該如何檢查它是否真的在股票雖然 - 這基本上只是遍歷集合,並打印出每個項目你沒有指定如何查看股市

+0

listBoxItem後沒有任何值屬性 – 2013-03-01 11:09:56

+0

請參閱我的編輯。改用ToString。 – Jeff 2013-03-01 11:12:26

+0

謝謝你的工作,我在做listbox1.items.ToString() – 2013-03-01 11:15:33

0

This'l工作,以及:

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

使用string.format方法與foreach局部變量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())); 
     } 
    } 
}   
+0

listBoxItem後沒有.value屬性 – 2013-03-01 11:12:12

+0

@AmritSharma fixed – CloudyMarble 2013-03-01 11:23:18

0

你可以在if子句中使用listBoxItem局部變量。