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(n开发者_Go百科ew 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
}
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]);
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>();
}
精彩评论