views:

1719

answers:

3

I want to pass values between two Forms (c#). How can I do it?

I have two forms: Form1 and Form2.

Form1 contains one button. When I click on that button, Form2 should open and Form1 should be in inactive mode (i.e not selectable).

Form2 contains one text box and one submit button. When I type any message in Form2's text box and click the submit button, the Form2 should close and Form1 should highlight with the submitted value.

How can i do it? Can somebody help me to do this with a simple example.

Thanks in advance Nagu

+3  A: 

There are several solutions to this but this is the pattern I tend to use.

//In Form1's button handler
using(Form2 form2 = new Form2()) 
{
  if(form2.ShowDialog() == DialogResult.OK) 
  {
    someControlOnForm1.Text = form2.TheValue;
  }
}

And...

//In Form2

//Create a public property to serve the value
public string TheValue 
{
  get { return someTextBoxOnForm2.Text; }
}
Jesper Palm
I thought this was bad code conduct. This is great then. I will also use this pattern
CasperT
A: 

declare string in form1 public string TextBoxString;

in form1 click event add

private void button1_Click(object sender, EventArgs e)
    {
        Form1 newform = new Form1();
        newform = this;
        this.Hide();
        MySecform = new Form2(ref newform);
        MySecform.Show();
    }

in form2 constructer

public Form2(ref Form1 form1handel)
    {
        firstformRef = form1handel;
        InitializeComponent();
    }

in form2 crate variable Form1 firstformRef;

private void Submitt_Click(object sender, EventArgs e)
    {
        firstformRef.TextBoxString = textBox1.Text;
        this.Close();
        firstformRef.Show();

    }
Shadow
+1  A: 

I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.

I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications

armannvg