2013-03-07 77 views
2

我有兩種形式,我想從Form2重新加載Form1中的組合框項目。 我將Form 1的窗體2的的MdiParent這樣的:從另一個表格重新加載組合框項目

Form2 f2 = new Form2(); 
f2.MdiParent = this; 
f2.Show(); 

我如何可以訪問內Form2的Form1的控制?

+0

:'((Form 1中)this.MdiParent).Combobox' – AbZy 2013-03-07 13:12:39

+0

退房這個問題:http://stackoverflow.com/questions/8566/最好的方式來訪問一個在另一個窗體中的控件 – 2013-03-07 13:12:50

+0

@defaultlocale該問題沒有任何可接受的答案 – Ehsan 2013-03-07 13:22:19

回答

2

試試這個,

String nameComboBox = "nameComboBoxForm1"; //name of combobox in form1 
ComboBox comboBoxForm1 = (ComboBox)f2.MdiParent.FindControl(nameComboBox); 
1

Form1,你需要像這樣定義一個屬性:在Load事件處理程序上Form2

Public ComboBox.ObjectCollection MyComboboxitems{ 
    get{ return {the Combox's name}.Items} 
} 

然後:

{name of form2 combobox}.Items = ((Form1)Me.MdiParent).MyComboboxitems; 

這是不要公開表單上的組合框的所有屬性,只是t他是你想要的。

在代碼示例中將{...}替換爲實際的對象名稱。

1

您可以在Form1中聲明一個公共靜態列表,並將其設置爲form1combobox的數據源,如下所示。

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     this.IsMdiContainer = true; 
    } 
    public static List<string> list; 
    private void button1_Click(object sender, EventArgs e) 
    { 
     Form2 frm2 = new Form2(); 
     frm2.MdiParent = this; 
     frm2.Show(); 
     comboBox11.DataSource = list; 
    } 
} 

在form2的加載事件中,將聲明的form1列表設置爲引用具有form2.combobox項目的新實例化列表。

public partial class Form2 : Form 
{ 
    public Form2() 
    { 
     InitializeComponent(); 
    } 
    List<string> list = new List<string> { "a", "b", "c" }; 
    private void Form2_Load(object sender, EventArgs e) 
    {    
     comboBox1.DataSource = list; 
     Form1.list = list; 

    } 
} 
1

試試這個:在窗口2類

Form1 f1 = (Form1)Application.OpenForms["Form1"]; 
ComboBox cb = (ComboBox)f1.Controls["comboBox1"]; 
cb.Items.Clear(); 
cb.Items.Add("Testing1"); 
cb.Items.Add("Testing2"); 
相關問題