Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send values from one form to another form

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.

like image 405
Nagu Avatar asked Oct 13 '09 11:10

Nagu


People also ask

How pass value from one form to another in WPF?

In this blog, I have a simple solution to pass value from one WPF form to another. Just make a overload constructor which takes parameters of the window in which you want to retrieve.


3 Answers

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

// Form 1
// inside the button click event
using(Form2 form2 = new Form2()) 
{
    if(form2.ShowDialog() == DialogResult.OK) 
    {
        someControlOnForm1.Text = form2.TheValue;
    }
}

And...

// Inside Form2
// Create a public property to serve the value
public string TheValue 
{
    get { return someTextBoxOnForm2.Text; }
}
like image 75
Jesper Palm Avatar answered Oct 06 '22 00:10

Jesper Palm


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

 public Form2(string qs)
    {
        InitializeComponent();
        textBox1.Text = qs;

    }
like image 24
nadi Avatar answered Oct 05 '22 22:10

nadi


Define a property

public static class ControlID {  
    public static string TextData { get; set; }
}

In the Form1

private void button1_Click(object sender, EventArgs e)
{  
    ControlID.TextData = txtTextData.Text;   
}

Getting the data in Form1 and Form2

private void button1_Click(object sender, EventArgs e)
{   
    string text=  ControlID.TextData;   
}
like image 27
shweta Avatar answered Oct 05 '22 23:10

shweta