Andre Catur Prasetyo
Andre Catur Prasetyo

Reputation: 43

Get comboBox value from another form in C#

I have 2 forms, in Form1 there is a button which will show Form2. in Form2 i have a comboBox. After selecting an item from comboBox, user can click Button to send a comboBox value to Form1 and Form2 will close.

Here my code:

Form1:

private void Button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2();
    frm2.ShowDialog();
}

Form2:

private void Button1_Click(object sender, EventArgs e)
{
    Form1 frm1 = new Form1();
    frm1.textBox1.Text = Convert.ToString(comboBox1.SelectedValue);

    this.DialogResult = DialogResult.OK;
}

But i the comboBox value doesn't appear at textBox on Form1saas

Upvotes: 2

Views: 8738

Answers (5)

Sami Dulger
Sami Dulger

Reputation: 1

You can set modifiers property in textbox. This property should be public.

Form 2 : `

public Form2()`
{
  InitializeComponent(); 
}

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
  Form1 frm = (Form1)Application.OpenForms["Form1"];
  frm.textBox1.Text = comboBox1.Text; this.Close(); 
}

Upvotes: 0

Sami Dulger
Sami Dulger

Reputation: 1

Try this code.

Form1:

    public void SetValue(string str)
    {
        textBox1.Text = str;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2(this);
        frm2.Show();
    }

Form2 :

readonly Form1 _ownerForm;

    public Form2(Form1 ownerForm)
    {
        InitializeComponent();
        this._ownerForm = ownerForm;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string selectedText = comboBox1.SelectedItem.ToString();
        this._ownerForm.SetValue(selectedText);
        this.Close();
    }

Upvotes: 0

Ur Marcelino
Ur Marcelino

Reputation: 61

try this on your button click event:

TextBox txt = (Form1)this.Owner.Textbox1;
txt.Text = combobox1.Text;
this.Close();

Upvotes: 0

Siamak Ferdos
Siamak Ferdos

Reputation: 3299

You should send refrence of this object to new Form.

Form1:

private void Button1_Click(object sender, EventArgs e)
{
    Form2 frm2 = new Form2(this);
    frm2.ShowDialog();
}

Form2:

Form _parentForm;

public Form2(Form frm)
{
     _parentForm = frm;
}

private void Button1_Click(object sender, EventArgs e)
{
    _parentForm.textBox1.Text = Convert.ToString(comboBox1.SelectedValue);

    this.DialogResult = DialogResult.OK;
}

Upvotes: 0

Samvel Avanesov
Samvel Avanesov

Reputation: 422

You are trying to set a value in the combobox of a new form, because you create it here:

Form1 frm1 = new Form1();

You should pass the reference to the Form1 instance into the Form2 (via constructor or member field).

The correct way to do it is to add a private member field of type Form1 to Form2 class, add a parameter to Form2 constructor, and initialize it on constructor call:

var form2 = new Form2(this);

Then reference the member field.

Upvotes: 2

Related Questions