Janet
Janet

Reputation: 1411

Object Reference not set to an instance or Index out of range error while adding values to lists

Below is my class file which have different names than the one that is used in the project.

public partial class College
{
public List<Students> Students;
}
public partial class Students
{
public List<Activity> Activity;
}
public partial class Activity{
public List<string> Name;
}

Below is my aspx.cs code

            College.Students.Add(new Students{ studentno= studentnumber.text});
            int index2 = College.Students.FindIndex(c => c.studentno== lineno);
            College.Students[index2].Activity= new List<Activity>();
            College.Students[index2].Activity.Add(new Activity{ });
            int k = (College.Students[index2].Activity.Count) - 1;

            College.Students[index2].Activity[k].Name = new List<string>();

            string ctrlStr = String.Empty;

            foreach (string ctl in Page.Request.Form)
            {
                if (ctl.Contains("Name"))
                {
                    ctrlStr = ctl.ToString();
                    College.Students[index2].Activity[k].Name[0] = (Request.Form[ctrlStr]);--- It errors out here...not understanding the reason...Am i missing any line of code

                }

Upvotes: 0

Views: 201

Answers (2)

Town
Town

Reputation: 14906

Object reference not set to an instance of an object

Change the declaration of the lists in your classes to:

public List<Students> Students = new List<Students>();

By doing simply public List<Students> Students; you're saying that Students exists but not actually setting it up (you're setting it to null) so you can't use any of the methods or properties that come with a List<T> until you initialise it.

Index out of range

This line throws an Index out of range

College.Students[index2].Activity[k].Name[0] 

because even though you've newed up Name to a List<string> you haven't added anything to it yet so you're trying to reference a non-existent index. Insetad of that, use:

College.Students[index2].Activity[k].Name.Add((Request.Form[ctrlStr]);

Upvotes: 1

Larry
Larry

Reputation: 18031

You need to initialize Lists

public partial class College
{
    public List<Students> Students = new List<Students>();
}
public partial class Students
{
    public List<Activity> Activity = new List<Activity>();
}
public partial class Activity{
    public List<string> Name = new List<string>();
}

Upvotes: 0

Related Questions