使用列表复选框中的值填充数组

Populating an array with values from list check boxes

我正在尝试用复选框中的值填充一个数组。我正在使用列表复选框。我花了几个小时才找到错误。我得到 NullReferenceException 未被用户代码处理。错误指向 i++ 代码位。当我评论 test[i]=item.Value;我++; lines 我可以提醒选择的值,但我不能将它们添加到数组中。

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

            }


        }
     }  

您需要实例化数组,但为此您必须有一个大小。我建议改用列表。

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

        }


    }
 }