Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing TextBox's text to another form in C#?

Tags:

c#

winforms

I have tried this to pass the information:

Form1 frm1 = new Form1(); 
 textBox1.Text = ((TextBox)frm1.Controls["textBox1"]).Text;

This is in the form load of the form getting the information. But there is no text. How do I fix this? Form2 is grabbing Form1's text and displaying it.

like image 937
Hunter Mitchell Avatar asked Nov 28 '22 09:11

Hunter Mitchell


2 Answers

I find Easy and Logical Way to Passing Text value one textbox to other in Windows Application.

In Second Form Write Code:-

    Create a Parameter of *Form2* Constructor.

    namespace PassingValue
    {
         public partial class Form2 : Form
         {
             public Form2(string message)
             {
                 InitializeComponent();
                 Textbox1.Text= message;
             }
         }
    }

In First Form Write Code:-

   Use the Parameter of Second Form in *First Form*:-

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

         private void Button1_Click(object sender, EventArgs e)
         {
             Form2 f2=new Form2(Textbox.Text);
             f2.Show();
         }
      }
   }
like image 35
Anmol Avatar answered Dec 18 '22 06:12

Anmol


Expose the contents of the textbox using a property:

class Form1 {
  public string MyValue {
    get { return textBox1.Text; }
  }
}

Then in Form2 do this:

var frm1 = new Form1();
frm1.ShowDialog(this); // make sure this instance of Form1 is visible
textBox1.Text = frm1.MyValue;

If you want frm1 to be constantly visible then make frm1 a class variable of Form2, and call .Show() in the constructor of Form2 for example.

like image 157
Herman Avatar answered Dec 18 '22 07:12

Herman