2012-01-07 116 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