This question already has an answer here:
这个问题在这里已有答案:
- What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it? 3 answers
什么是IndexOutOfRangeException / ArgumentOutOfRangeException以及如何解决它? 3个答案
I try this code to display names from database in loop but this shows an error index was outside the bounds of the array meaning on this line name[j++] = Convert.ToString(reader["CategoryName"]);
我尝试使用此代码在循环中显示数据库中的名称,但这显示错误索引超出了此行名称的数组边界[j ++] = Convert.ToString(reader [“CategoryName”]);
code
con.Open();
int count =0;
int j =0;
//cmd = new SqlCommand("select * from Category");
string[] name = new string[count];
cmd = new SqlCommand("select CategoryName from Category",con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
name[j++] = Convert.ToString(reader["CategoryName"]);
}
int loc = 37;
CheckBox[] obj = new CheckBox[count];
for (int i = 0; i < count; i++)
{
obj[i] = new CheckBox();
obj[i].Location = new System.Drawing.Point(loc, 50);
obj[i].Size = new System.Drawing.Size(80, 17);
obj[i].Text = name[i];
this.Controls.Add(obj[i]);
loc += 80;
}
con.Close();
any help?
2 个解决方案
#1
0
Well you set count = 0
then you create an array with that
那么你设置count = 0然后你用它创建一个数组
string[] name = new string[count];
Which means your array will be of 0 lenght and you won't be able too assign anything to it. I suggest you change it to a List
which will be much easier
这意味着你的数组将是0长度,你将无法分配任何东西。我建议你把它改成一个更容易的List
List<string> name = new List<string>();
while (reader.Read())
{
name.Add(Convert.ToString(reader["CategoryName"]));
}
#2
1
At the beggining you set
在开始你的设定
int count =0;
and then you initialize the array like this:
然后你像这样初始化数组:
new string[count];
you are effectively creating an array with zero places in it. and then you loop with:
你正在有效地创建一个零位置的数组。然后你循环:
name[j++]
you access an index in the array that isn't there
您访问不存在的数组中的索引
#1
0
Well you set count = 0
then you create an array with that
那么你设置count = 0然后你用它创建一个数组
string[] name = new string[count];
Which means your array will be of 0 lenght and you won't be able too assign anything to it. I suggest you change it to a List
which will be much easier
这意味着你的数组将是0长度,你将无法分配任何东西。我建议你把它改成一个更容易的List
List<string> name = new List<string>();
while (reader.Read())
{
name.Add(Convert.ToString(reader["CategoryName"]));
}
#2
1
At the beggining you set
在开始你的设定
int count =0;
and then you initialize the array like this:
然后你像这样初始化数组:
new string[count];
you are effectively creating an array with zero places in it. and then you loop with:
你正在有效地创建一个零位置的数组。然后你循环:
name[j++]
you access an index in the array that isn't there
您访问不存在的数组中的索引