0

I'm trying to get data from the database and put it in a list. Then, i want to create dropdown list with the received data.

The db table:

ID
projectName

The code:

public void ProjectsList()
{
    List<ProjectsListClass> ProjectsList=new List<ProjectsListClass>(); //list of projects
    ProjectsListClass projectDetails=new ProjectsListClass();//1 project details

    //creating session of projects table
    using (SqlConnection conn = new SqlConnection(mainDBConn))//connect to the database table
    {
        SqlCommand sqlProjectsList = new SqlCommand("SELECT * FROM dbo.Projects ORDER BY projectName", conn);

        conn.Open();

        SqlDataReader rsProjectsList = sqlProjectsList.ExecuteReader();

        if (rsProjectsList.HasRows && rsProjectsList.Read())//there is a project, insert into the array
        {
            projectDetails.ProjectsListProjectID = Convert.ToInt16(rsProjectsList["ID"]);
            projectDetails.ProjectsListProjectName = rsProjectsList["projectName"].ToString();
            ProjectsList.Add(projectDetails);
        }
        Session["ProjectsList"] = ProjectsList;

        rsProjectsList.Close();
        conn.Close();
    }  
}

and in the other page:

    List<ProjectsListClass>projectsArray=new List<ProjectsListClass>();
    projectsArray=(List<ProjectsListClass>)Session["ProjectsList"];

    foreach(var project in projectsArray)
    {
        ListItem l = new ListItem(project.ProjectsListProjectID.ToString()
            , project.ProjectsListProjectName.ToString()
            , true);
        projectIDDropDownList.Items.Add(l);
    }

i get the error:

Object reference not set to an instance of an object.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 20: foreach(var project in projectsArray) - this one in red

Line 21: { Line 22: ListItem l = new ListItem(project.ProjectsListProjectID.ToString()

What should i do?

Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69
Nadav
  • 49
  • 7
  • 1
    Use the debugger attachment, you can see what component is null by hovering above it. Probablty one of the properties is not set – PieterSchool Apr 17 '15 at 10:44
  • 2
    Where is `ProjectsList()` called? – Gabriel Negut Apr 17 '15 at 10:45
  • 2
    Related: [What is a `NullReferenceException` and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Soner Gönül Apr 17 '15 at 10:48
  • if you don't want to get error just check if `projectsArray` on "other page" has some values like this : `if(projectsArray.Any()){ // if yes - add items to dropdown }` – demo Apr 17 '15 at 10:48
  • well, the ProjectsList() is a method in "SiteMaster" page.. i'm calling it in the page_load protected void Page_Load(object sender, EventArgs e) { ProjectsList(); – Nadav Apr 17 '15 at 10:51
  • @Nadav Have you tried stepping tru with the debugger? – PieterSchool Apr 17 '15 at 10:52
  • @demo any has no use, if there are none the foreach will just skip it most likeley the properties of the object are not set – PieterSchool Apr 17 '15 at 10:53
  • how do i use the debugger for this? the problem is that the data don't go to the list (if it's null..) – Nadav Apr 17 '15 at 10:53
  • in `ProjectsList` method, you're not cycling through each row in the reader. change it to this: ` if (reader.HasRows) { while (rsProjectsList.Read())//there is a project, insert into the array { ProjectsListClass projectDetails=new ProjectsListClass() projectDetails.ProjectsListProjectID = Convert.ToInt16(rsProjectsList["ID"]); projectDetails.ProjectsListProjectName = rsProjectsList["projectName"].ToString(); ProjectsList.Add(projectDetails); } }` and remove at the top: `ProjectsListClass projectDetails=new ProjectsListClass();//1 project details` – hynsey Apr 17 '15 at 10:56
  • @Nadav 1st awnser: http://stackoverflow.com/questions/848987/attach-debugger-to-iis-instance – PieterSchool Apr 17 '15 at 10:56
  • You are filling the data in your list in a page and you are calling it in your page master. but the problem is that the page_load of page master will be executed the first . – Ghassen Apr 17 '15 at 11:05
  • i used the while... still nothing... and about the master page.. that's right.. i want to create the session with the masterpage, then i'm just using the session in other pages – Nadav Apr 17 '15 at 11:09
  • when i'm trying to do "if (projectsArray.any())" the compiler says: value cannot be null – Nadav Apr 17 '15 at 11:13
  • It's obvious that `projectsArray` is NULL so you cannot use `.Any()`. So the question is: why is `projectsArray` NULL? Most likely because there's nothing in `Session["ProjectsList"]`. Check that the session gets filled before you fetch any values from it. (BTW almost every line of code you've posted contains a bad practice: SELECT *, `SqlCommand` etc not encapsulated in `using`, bad naming, not databinding your dropdownlist,... You should really fix these issues.) – BCdotWEB Apr 17 '15 at 11:20
  • i didn't understand the bad practice issues you said... :/ and why does the session doesn't get the data? – Nadav Apr 17 '15 at 11:25
  • i think the problem is in the session. it's like it doesn't change... the use of it is ok? there is no "session["name"]=new session();" command in asp.net? – Nadav Apr 17 '15 at 11:34
  • now it works... but the session issue is a problem for me, i don't know how to use it currectly... if (projectsArray != null) { foreach (var project in projectsArray) { ListItem l = new ListItem(project.ProjectsListProjectName.ToString() , project.ProjectsListProjectID.ToString(), true); projectIDDropDownList.Items.Add(l); } } – Nadav Apr 17 '15 at 11:38

1 Answers1

0

I think there's a few things you need to be mindful of.

Although I don't know you're particular requirements, generally speaking I don't believe storing the your projectlist in session is the best approach. Generally I would have a Project Class with a GetProjectList() method that return a List of Projects. You could then call this method from your "other" page and bind to your DropDownList.

Also, I believe you may have your projectDetails declaration in the wrong place. If you want to return a list of projects try something like this (I'm a VB developer but I've had a go at the C#).

SqlCommand sqlProjectsList = new SqlCommand("SELECT * FROM dbo.Projects ORDER BY projectName", conn);

conn.Open();

SqlDataReader rsProjectsList = sqlProjectsList.ExecuteReader();

if (rsProjectsList.HasRows)//there is a project, insert into the array
{
   while rsProjectsList.Read()
   {
      ProjectsListClass projectDetails=new ProjectsListClass();
      projectDetails.ProjectsListProjectID = Convert.ToInt16(rsProjectsList["ID"]);
      projectDetails.ProjectsListProjectName = rsProjectsList["projectName"].ToString();
      ProjectsList.Add(projectDetails);
   }
}

rsProjectsList.Close();
conn.Close();

To bind to your dropdown list, try the following code,

projectIDDropDownList.DataSource = Project.GetProjects();
projectIDDropDownList.DataBind();
scm8jet
  • 66
  • 5
  • ok thank you, i'll probably use it for some other things in my web site... thank you all for the quick and good comments :) – Nadav Apr 17 '15 at 12:43