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.
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.
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; }
}
                        private void button1_Click(object sender, EventArgs e)
{
        Form2 frm2 = new Form2(textBox1.Text);
        frm2.Show();    
}
 public Form2(string qs)
    {
        InitializeComponent();
        textBox1.Text = qs;
    }
                        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;   
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With