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


below class file have different names 1 used in 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 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]);--- errors out here...not understanding reason...am missing line of code                  } 

object reference not set instance of object

change declaration of lists in classes to:

public list<students> students = new list<students>(); 

by doing public list<students> students; you're saying students exists not setting (you're setting null) can't use of methods or properties come list<t> until initialise it.

index out of range

this line throws index out of range

college.students[index2].activity[k].name[0]  

because though you've newed name list<string> haven't added yet you're trying reference non-existent index. insetad of that, use:

college.students[index2].activity[k].name.add((request.form[ctrlstr]); 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -