views:

67

answers:

2

When creating a new project, i want this project to become available from a dropdown. The first project i create, works, and is placed as the menu item as well as a dropdown item, however when i try to add the next dropdown item it crashes and tells me "Object reference not set to an instance of an object."

This line creates the exception: ProjectToolStripMenuItem.DropDownItems.Add(newproject);

ArrayList projects = new ArrayList();

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{    
   Project moldProject = new Project();    
   moldProject.ProjectName = "unnamed";

   ToolStripMenuItem ProjectToolStripMenuItem = null;

   if (projects.Count == 0)
   {
       ProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();

       ProjectToolStripMenuItem.Name = "projectToolStripMenuItem";
       ProjectToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
       ProjectToolStripMenuItem.Text = "unnamed*";

       this.menuStrip1.Items.Add(ProjectToolStripMenuItem);
   }

   ToolStripMenuItem newproject = new System.Windows.Forms.ToolStripMenuItem();

   string name = "aboutToolStripMenuItem" + (projects.Count + 1).ToString();
   newproject.Name = name;

   newproject.Size = new System.Drawing.Size(211, 22);
   newproject.Text = "unnamed*";

   ProjectToolStripMenuItem.DropDownItems.Add(newproject);

   projects.Add(moldProject);
}
A: 

ToolStripMenuItem ProjectToolStripMenuItem = null;

Should have been declared outside the method. Sorry for the inconvinience.

/Thomas

Bildsoe
A: 

Your ProjectToolStripMenuItem is set to null and it only gets assigned a value if the projects.Count is equal to zero. This is why you get the null reference exception for the second project. Since projects.Count is not zero, ProjectToolStripMenuItem never gets assigned.

msergeant