2012-01-07 119 views
1

我試圖去具體的項目在ListBox(asp.net,C#) 並檢查它是否是空或不是:ListBox中獲取特定項目的值

if (ListBox.Items[0] == null) 
{ 
    if (HowMany.Text == arrOfWords[0]) 
    { 
      ListBox.Items.Add(arrOfWords[0]); 
      ErrorMessege.Text = "Good!"; 
    }      
} 

它返回的是:指數超出範圍。必須是非負數且小於集合的大小。 參數名稱:索引

這是爲什麼? 謝謝!

回答

1

在訪問數組元素之前添加一個空檢查。

if ((ListBox.Items.Count > 0) && (ListBox.Items[0] == null)) 
{ 
    if((arrOfWords.count>0)&&(arrOfWords[0]!=null)) 
     { 
      if (HowMany.Text == arrOfWords[0]) 
      { 
       ListBox.Items.Add(arrOfWords[0]); 
       ErrorMessege.Text = "Good!"; 
      } 
     } 
} 

編輯:從您的評論「其確定有0項有我,我的意思是,如果有0項存在,那麼它應該從arrOfWords添加項目

所以,如果你的意思是,即使有ListBox中的零項,你需要從數組列表框中添加一個項目,然後取出首先,如果條件

if((arrOfWords.count>0)&&(arrOfWords[0]!=null)) 
{ 
    if (HowMany.Text == arrOfWords[0]) 
    { 
     ListBox.Items.Add(arrOfWords[0]); 
     ErrorMessege.Text = "Good!"; 
    } 
} 
+0

在調試模式下,它甚至沒有輸入第一個if語句。即使我試圖讓if((ListBox.Items.Count> 0)&&(ListBox.Items [0] == null)) – thormayer 2012-01-07 01:52:20

+1

在第一個if條件中放置斷點並查看列表框中存在多少項和arrOfWords – Shyju 2012-01-07 01:54:00

+0

默認情況下,列表框在應用程序第一次運行時呈現0個項目,而「arrOfWords」每次至少呈現一個。 – thormayer 2012-01-07 01:57:16

1

看起來在這種情況下Items集合是空的,因此即使0超出集合範圍。您需要測試索引是否有效以及該項是否爲非空。

if (ListBox.Items.Count > 0 && ListBox.Items[0] == null) { 
    ... 
} 
+0

毫米..仍然得到相同的錯誤信息,如果我嘗試.. – thormayer 2012-01-07 01:52:43

+1

然後它可能是其他指標之一。我會嘗試所有這些修補程序。 – JaredPar 2012-01-07 02:21:41