Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data between forms

Tags:

c#

winforms

I have two forms. First, Form1 has a group box, some labels and a listbox. I press a button and new Form2 is opened and contains some text. I want to transfer the text in Form2 to the listbox in the Form1.

So far, what I have done is make modifier of listbox to public and then put this code in the button of Form2

Form1 frm = new Form1();
frm.ListBox.items.Add(textBox.Text);

But amazingly, this does not add any value. I thought I was mistaken with the insertion so I made the same procedure. This time, I made a label public and added textbox value to its Text property but it failed.

Any ideas?

like image 758
Afnan Bashir Avatar asked Jan 03 '11 20:01

Afnan Bashir


2 Answers

Let's assume Form1 calls Form2. Please look at the code:

Form1:

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2();
        frm.Show();
        frm.VisibleChanged += formVisibleChanged;


    }

    private void formVisibleChanged(object sender, EventArgs e)
    {
        Form2 frm = (Form2)sender;
        if (!frm.Visible)
        {
            this.listBox1.Items.Add(frm.ReturnText);
            frm.Dispose();
        }


    }

}

Form2:

 public partial class Form2 : Form
{

    public string ReturnText { get; set; }

    public Form2()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.ReturnText = this.textBox1.Text;
        this.Visible = false;

    }


}

The answer is to declare public property on Form2 and when form gets hidden. Access the same instance and retrieve the value.

like image 184
Kamil Krasinski Avatar answered Oct 05 '22 10:10

Kamil Krasinski


Please avoid the concept of making any public members like you said >>i have done is make modifier of listbox to public and then in form2 in button code<< this is not a good practice,on the other hand the good one is in Brad Christie's Post,I hope you got it.

like image 38
Ismaiel Saleh Avatar answered Oct 05 '22 10:10

Ismaiel Saleh