Using The Controls Of One Form Into Another
c#, oop, winforms
Solution
Depending on how you launch the second form you can either assign a member object in Form2 that references Form1 or if you are using an MDI interface there is a forms collection from which you can retrieve a reference to your Form1.
For example, you could have the following code in your Form2 class:
public partial class Form2 : Form
{
public Form1 LaunchOrigin { get; set; }
// and so on
Now you can assign the LaunchOrigin member when you launch Form2. Here is an example:
Form2 newForm = new Form2();
newForm.LaunchOrigin = this;
newForm.Show();
You now have access to Form1 and all its members. Here is a simple example of that:
private void Form2_Load(object sender, EventArgs e)
{
this.Text = LaunchOrigin.Text;
}
You must remember that controls are declared as private so you won't have direct access to them. You could write a property on Form1 that referenced that control but this is most often a bad idea. For the sake of completeness, however, here is some code that you could use to expose a button on Form1:
public partial class Form1 : Form
{
public Button theButton;
public Form1()
{
InitializeComponent();
theButton = button1; // where button1 is what I dragged on
}
// and so on
Although what you're asking is relatively easy to accomplish, it puts you on the road to some brittle application structure. Think hard about what it is you're trying to expose between forms, perhaps it deserves to be a distinct type that you can bind to both forms so that once you change the underlying type, you change the representation on both.
Problem
I have a application that in one form(`Form1`) I have many checkBoxes and textBoxes and in `Form2` I have only a textBox, but I want to put some contents from the `Form1` textBoxes and put in the `Form2` textBox, like this, but between forms: ``` textBox1.Text = "Test: " + textBox1 + "\n" + textBox3; ``` As `textBox1` in `Form2` and the second `textBox1` and `textBox3` in `Form1`, but how I can do this? Thanks.