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

时间:2015-03-11 21:04:28

标签: c# asp.net arrays nullreferenceexception

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

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

            }


        }
     }  

1 个答案:

答案 0 :(得分:0)

您需要实例化数组,但为了做到这一点,您必须具有大小。我建议改用List。

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

        }


    }
 }  
相关问题