Dannz
Dannz

Reputation: 495

Showing the same comboBox in two forms

I couldn't find anything similar to this, I have a combo box in the main window form and I want to pass the same combo box to another form and change it values there so it will change in the main window accordingly.

I am new to C# apologies for ignorance, I've tried the following:

In main window:

private void companiesToolStripMenuItem_Click(object sender, EventArgs e)
{
    ModifyCompanies childForm = new ModifyCompanies(this);
    childForm.ShowDialog();
}

In the second form: I've built a constructor and thought it would work but the items don't display even if it's the same comboBox.

public ModifyCompanies(MainWindow mainWindow)
{
    this.mainWindow = mainWindow;
    InitializeComponent();
    comboBox1 = mainWindow.companyComboBox;
}

Upvotes: 0

Views: 403

Answers (1)

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

Passing controls to different forms may be a bad idea, I suggest sharing data between forms, something like the following sample :

public class SharedData
{
    public List<string> TestData { get; set; } 

    public SharedData()
    {
        TestData = new List<string>();
    }
}

And in your program class :

class Program
{
    public static SharedData Shared {get; set;}

    [STAThread]
    static void Main()
    {
        Shared = new SharedData();

        Shared.TestData.Add("test1");
        Shared.TestData.Add("test2");
        Shared.TestData.Add("test3");

        System.Windows.Forms.Application.EnableVisualStyles();
        System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
        System.Windows.Forms.Application.Run(new Form1());
    }
}

And inside the form it would be something like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        comboBox1.DataSource = Program.Shared.TestData;
    }
}

Other form will be the same and you can manipulate the data from the two forms and the data will be updated for both.

Hope this is useful.

Upvotes: 2

Related Questions