Form1: Add combobox item from another form2: textbox Pin

  • 565 Views
  • Last Post 29 March 2018
arrow_hit posted this 28 March 2018

Dear all,

I can not handle this. Can you help me?

Thanks

Form1 has combobox and a button to open Form 2

Form 2 has textbox and a button to OK&Exit

I want to add text value from Form2 to Form1 combobox.

admin posted this 29 March 2018

You can use singleton pattern to solve the problem as below

Modify your code in Form1 as below

public partial class Form1 : Form
{
    static Form1 _instance;
    public static Form1 Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Form1();
            return _instance;
        }
    }

    public void AddItemToCombobox(object value)
    {
        comboBox1.Items.Add(value);
    }

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (Form2 frm = new Form2())
        {
            frm.ShowDialog();
        }
    }

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

Open your Form2 then code to OK button as below

private void button1_Click(object sender, EventArgs e)
{
    Form2.Instance.AddItemToCombobox(textBox1.Text);
    textBox1.Clear();
}

TextBox, Button in Form2 i'm using default name, similar Form1

I hope you can solve your problem

Close