将项目从另一个表单添加到ToolStripMenuItem下拉列表中

问题描述:

我正在使用Visual Studios创建Windows窗体应用程序。我的系统负责创建和查看大学的模块信息。但是,目前虽然当我的系统启动它将填充工具条菜单我需要一种方式添加新项目时,它们创建列表。新的记录是在不同的表单上创建的,我无法弄清楚如何从创建Form2的Form1中将项目添加到Form1上的ToolStripDropdown(请参阅下面的示例)。我试图简单地使ToolStripMenuItem公开,但不起作用。谁能帮我吗?将项目从另一个表单添加到ToolStripMenuItem下拉列表中

The ToolStrip as present of ToolStrip1

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO; 

namespace Mod_Note_2._0 
{ 
    public partial class Form2 : Form 
    { 
     public string newmodcode; 
     public string baseText = "Enter information related to the module section here"; 

     public string newmodtitle; 
     public string newmodsyn; 
     public string newmodlo; 
     public string newmodassign; 

     public Form2() 
     { 
      InitializeComponent(); 
     } 

     private void label1_Click(object sender, EventArgs e) 
     { 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      newmodcode = NewModuleCode.Text; 

      //Adds the file path and name to the module code to create the file names 
      newmodtitle = newmodcode + "title.txt"; 
      newmodsyn = newmodcode + "synopsis.txt"; 
      newmodlo = newmodcode + "LOs.txt"; 
      newmodassign = newmodcode + "assignments.txt"; 

      //Adds the file path the new module code so it can create the file 
      string newmodcodepath = newmodcode + "code.txt"; 

      //Creates the new files with the filler text as default 
      File.WriteAllText(newmodcodepath, newmodcode); 
      File.WriteAllText(newmodtitle, baseText); 
      File.WriteAllText(newmodsyn, baseText); 
      File.WriteAllText(newmodlo, baseText); 
      File.WriteAllText(newmodassign, baseText); 

添加项目下拉电流代码:

ToolStripItem newDropDownItem = new ToolStripMenuItem(); 
       newDropDownItem.Text = newmodcode; 

       Form1.modulesToolStripMenuItem.DropDownItems.Add(newDropDownItem); 
  Close(); 
     } 

     //Simple cancelation sequence closing the entry form 
     private void button2_Click(object sender, EventArgs e) 
     { 
      Close(); 
     } 
    } 
} 
+0

你必须在第二个形式第一种形式的参考。像这样:http://stackoverflow.com/a/38460510/3185569 – user3185569

我回答在这里(https://stackoverflow.com/a/32916403/5378924),如何从一个添加一些控件形式到另一个。

Form1中:

public partial class Form1 : Form 
{ 
    public static Form1 Instance { get; private set; } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
      Instance = this; 
    } 
} 

窗体2:

ToolStripItem newDropDownItem = new ToolStripMenuItem(); 
newDropDownItem.Text = newmodcode; 
Form1.Instance.modulesToolStripMenuItem.DropDownItems.Add(newDropDownItem); 
+0

这样,打开Form1的下一个实例后,Instance属性将指向新的表单。 –

+0

看看[这些选项](http://stackoverflow.com/a/38552832/3110834),你会发现它们很有用:) –

+0

@RezaAghaei我认为,Form1会一直保留,直到用户关闭应用程序。 Form1是应用程序的起点,它只打开和关闭一次。 –