0

Return this error "Object reference not set to an instance of an object Error" when trying to add item in list. In the other words it's return error in addtoNote.Add(Name); and am sure that Name is not null.

protected void features(string Name, string shortName)
{ List<string> addtoNote =  ViewState["Note"] as List<string> ;
    if (Name.Length > 0)
    {
        addtoNote.Add(Name);
    } else
    {for (int x = 0; x < addtoNote.Count; x++)
        {if (addtoNote[x].StartsWith(shortName))
            {
                addtoNote.RemoveAt(x);}
        } }
    ViewState["Note"] = addtoNote;
    TxtNote.Text = string.Join(TxtNote.Text , ",", addtoNote);
}
protected void ChkPersonalAccedent_CheckedChanged(object sender, EventArgs e)
{if (ChkPersonalAccedent.Checked == true)
    { features("حوادث شخصية", "حوادث شخصية");}
    else
     { features("", "حوادث شخصية"); }}
rere
  • 41
  • 1
  • 12

1 Answers1

1

If ViewState["Note"] is not a List<string>, this expression

ViewState["Note"] as List<string>;

will return null. So addtoNote is null and that is why the runtime exception is thrown.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109