# How To Access A Textbox On One Form From Another Form?



## char[] rager (Aug 30, 2010)

I have read many forums and answers on the Internet and since I will not be taking C#.NET at my university until later, I still want to know how to modify a textbox on my main form from another form.

I am making an automatic code generator for HTML, and on my main form I have a textbox showing the HTML code currently in a .html file. On my main form, I also have a button to access a code editor, which I put into a different windows form.

Now, whenever I make code changes in my code editor, save it, and exit that windows form, what do I write in that formClosing or formClosed event handler to update the textbox on my MAIN form? By the way, I have already set that textbox to public status.


----------



## FordGT90Concept (Aug 30, 2010)

You have to either put in a property or make the textbox object public.  Then you can access it via InstanceOfOwningForm.NameOfTextbox.

E.g.

```
public class MainForm : Form
{
   private TextBox _DisplayBox = new TextBox();

  public MainForm()
  {
    InitializeComponent();

    ChildForm frm = new ChildForm();
    frm.ShowDialog();
    _DisplayBox.Text = frm.EditableText;
  }
}

public class ChildForm
{
  private TextBox _MyTextBox = new TextBox();
  public string EditableText
  {
    get { return _MyTextBox.Text; }
    set { _MyTextBox.Text = value; }
  }
}
```

The other alternative is to make a static class and a variable static to hold the value.  Static means it is owned by the class instead of the object.


```
public static class Static
{
  public static string EditableText;
}

public class MainForm : Form
{
   private TextBox _DisplayBox = new TextBox();

  public MainForm()
  {
    InitializeComponent();

    ChildForm frm = new ChildForm();
    frm.ShowDialog();
    _DisplayBox.Text = Static.EditableText;  // Reads the value and displays it.
  }
}

public class ChildForm
{
  private TextBox _MyTextBox = new TextBox();
  public Childform()
  {
    Initialize Component();
    
    this.FormClosing += new FormClosingEventHandler(this.MainForm_FormClosing);
  }
  
  private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
  {
    Static.EditableText = _MyTextBox.Text; // Sets the text.
  }
}
```


----------



## char[] rager (Aug 31, 2010)

Thank you FordGT90Concept. I got it to work


----------

