0

I am trying to populate an array with values from check boxes. I am using list check boxes. I spent hours to find the error. I am getting NullReferenceException was unhandled by user code. The error is pointing to i++ bit of code. When I comment test[i]=item.Value; and i++; lines I can alert the values that are selected but I cannot add them into the array.

protected void Button1_Click(object sender, EventArgs e)
        {

        string []test=null;

        int i = 0;

        foreach (ListItem item in CheckBoxList1.Items)
        {

            if (item.Selected)
            {
                // oneSelected = true;

                test[i]=item.Value;
                i++;

                Response.Write("<script LANGUAGE='JavaScript' >alert('"+item.Value+"')</script>");

            }


        }
     }  
John Saunders
  • 160,644
  • 26
  • 247
  • 397
userMilka
  • 37
  • 1
  • 7
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Mar 11 '15 at 21:15

1 Answers1

0

You need to instantiate the array but in order to do this you must have a size. I recommend using a List instead.

protected void Button1_Click(object sender, EventArgs e)
    {

    var test = new List<string>();

    foreach (ListItem item in CheckBoxList1.Items)
    {

        if (item.Selected)
        {
            // oneSelected = true;

            test.Add(item.Value);

            Response.Write("<script LANGUAGE='JavaScript' >alert('"+item.Value+"')</script>");

        }


    }
 }  
mambrow
  • 442
  • 5
  • 14