Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

Multiple Forms

I have two forms showing on the screen, Form1 and Form2.  On Form1 I have a textbox which is blank. On form2 I have a command button which will enter text into the textbox on Form1. It's not working. So the question is this; How do I enter text into the textbox on Form1 from Form2 with both forms showing on the screen?.

Stan Anderson
Friday, December 10, 2004

If you are talking about WinForms, you would have to expose a public method on your Form1 that would then set the textbox.

Something like:

//On Form1
public void SetText(string message)
  textbox1.Text = message;

Then Form2 would call that method:

//On Form2
Form1 form1  = new Form1();
form1.SetText("Hello, world");

Now, if Form1 isn't instatiated by Form2, then you will have to either have a third form to act as an intermediary, or create some sort of a static method on Form1.  Another option would be to have Form2 fire an event and register Form1 as a listener. You could also pass a callback reference to Form1 in the constructor of Form2:

public Form2(Form1 form1)
  this.form1 = form1;

But I would question why the two need to be so tightly coupled. The entire design of it smells to me.

Cory Foy (
Friday, December 10, 2004

If form1 is the form that creates form2, then when creating form2, do it like this:

Form2 NewForm2 = new Form2();
Form2.Owner = this;

Next, to access form1 from form2, use:

((Form1) Owner).SetText("blah");

Replace the settext call with whatever public method, property or variable that you want to expose.

Michael Feldkamp
Friday, December 17, 2004

I would like to add that if you are doing this, you might want to look at your app's design in general... I have only had a (good) reason to do this once or twice, and even on those occasions I probably could have altered my design to allow for a prettier solution.

Michael Feldkamp
Friday, December 17, 2004

*  Recent Topics

*  Fog Creek Home