简体   繁体   中英

Reload combobox items from another form

I have two forms, I want to reload combobox items in Form1 from Form2. I set Form1 as MdiParent of Form2 like this:

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

How can I access Form1 controls from within Form2?

Try this,

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

on Form1 you need to define a property like this:

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

Then on Form2 in the Load event handler:

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

This is to not expose all the properties of the combobox on form one, just the one you want.

In the code examples replace {...} with the actual object names.

You can declare a public static List in Form1 and set it to the datasource of form1combobox as shown here.

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;
    }
}

In the load event of form2, set the declared form1 list to refer to new instantiated list having the items of 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;

    }
}

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM