创建新项目时,我希望此项目可从下拉列表中获得。第一个项目我创建,工作,并作为菜单项和下拉项放置,但是当我尝试添加下一个下拉项时,它崩溃并告诉我“对象引用未设置为对象的实例”。
此行创建例外: 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);
}
答案 0 :(得分:0)
ToolStripMenuItem ProjectToolStripMenuItem = null;
应该在方法之外声明。很抱歉给您带来不便。
/托马斯
答案 1 :(得分:0)
ProjectToolStripMenuItem设置为null,如果projects.Count等于零,则只会为其分配值。这就是为什么你得到第二个项目的空引用异常。由于projects.Count不为零,因此永远不会分配ProjectToolStripMenuItem。