参数超出范围列表框

时间:2015-06-29 01:00:34

标签: c# visual-studio-2012

我在计时器上收到以下错误

InvalidArgument=Value '1' is not a valid value for 'index'.

string lista = listBox1.Items[bz].ToString();
bz++;
string[] split = lista.Split(';');
numero.Text = split[0];

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在C#中,All Collection(Array,List,...)范围是0到Count - 1.例如,您有一个包含1,000个项目的数组。在这种情况下,数组的范围是0到999。

在访问像这样的集合元素时,您必须检查验证。 (这不是可选的,强烈建议这样做)

if ( bz < 0 || bz >= listBox1.Items.Count ) {
    /* Index is out of bound */
} else {
    /* You can safely access to elements */
}
顺便说一下,你的问题是:

  1. 您在ListBox中没有足够的项目。 (如何将项目添加到ListBox?)
  2. 您没有检查 bz 的验证。 (索引变量)