Search code examples
c#buttonnewforms

How to code a button to enter a value in a textbox on another form


I have form 1 with 4 buttons when I click a button it opens a new form. Each button opens the same form but I want the corresponding button to enter specific values into two different text boxes on form 2.

Form 1 Button A; Form2 textbox1= 400 textbox2 =0.4

Form 1 Button B; Form2 textbox1= 350 textbox2 =0.9

Form 1 Button C; Form2 textbox1= 700 textbox2 =0.6

Form 1 Button D; Form2 textbox1= USER DEFINED textbox2 = USER DEFINED

How would I go about this

 //This is the current text
 // Form1:   
private void ButtonA_Click(object sender, EventArgs e)
    {
           Form2 numb = new form2();
           numb.FormClosed += new FormClosedEventHandler(numb_FormClosed);
           this.Hide();
           CalcForm.Show();
    }

Solution

  • You can just set the value of the required textBox from the first form like below, but before it make sure that you have set that textBox to be internal so that you can access it from first form(in the Form.Designer.cs):

    internal System.Windows.Forms.TextBox textBox1;
    

    and

    private void ButtonA_Click(object sender, EventArgs e)
    {
           Form2 numb = new form2();
           numb.FormClosed += new FormClosedEventHandler(numb_FormClosed);
           numb.textbox1.Text = "400";
           numb.textbox2.Text = "0.4";
           this.Hide();
           CalcForm.Show();
    }
    

    Another approach is to define parameterized constructor for Form2 and set the value of the TextBox in that constructor like below:

    public Form2(string a,string b)
    {
        textBox1.Text = a;
        textBox2.Text = b;
    }
    

    and

    private void ButtonA_Click(object sender, EventArgs e)
    {
           Form2 numb = new form2("aaaa","bbbb");
           numb.FormClosed += new FormClosedEventHandler(numb_FormClosed);
           this.Hide();
           CalcForm.Show();
    }