【问题标题】:Populating an array with values from list check boxes [duplicate]使用列表复选框中的值填充数组[重复]
【发布时间】:2015-05-13 21:00:37
【问题描述】:

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

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

            }


        }
     }  

【问题讨论】:

标签: c# asp.net arrays nullreferenceexception


【解决方案1】:

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

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

        }


    }
 }  

【讨论】:

  • 感谢它现在正在工作
猜你喜欢
  • 2017-04-24
  • 2019-01-05
  • 2015-11-20
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多