-2

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"]);

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?

Super
  • 23
  • 1
  • 8
  • You are initializing your `name` array with a size of `0` – Rufus L Apr 05 '17 at 17:44
  • You declare `int count = 0;` and then `string[] name = new string[count];` So name is zero characters long. You then access it and try to write to that zero length array. What would you expect to happen? I know! You'll get an error that says **Index was outside the bounds of the array**. Do I win a prize? – Ken White Apr 05 '17 at 17:44
  • You initialize `name` as an array with 0 size. Then you try to access an index of your array **which has 0 size** and wonder why you got an index out of bounds exception? Maybe do some googling to make an effort to better understand what the exception is, why it happens, and how to fix it. – tnw Apr 05 '17 at 17:45

2 Answers2

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

Fadi Banna
  • 554
  • 1
  • 10
  • 26
0

Well you set count = 0 then you create an array with that

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

List<string> name = new List<string>();

while (reader.Read())
{
    name.Add(Convert.ToString(reader["CategoryName"]));
}
I.B
  • 2,925
  • 1
  • 9
  • 22
  • ok and how to display that name in label? – Super Apr 05 '17 at 17:56
  • @Super You can access the `List` the same way as the array by doing `name[i]`. You can get the amount of items in your list by doing `count = name.Count;` – I.B Apr 05 '17 at 18:00