2016-07-24 90 views
0

我正在使用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

回答

0

我回答在這裏(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是應用程序的起點,它只打開和關閉一次。 –

相關問題