tags:

views:

54

answers:

3

I would like to have direct access to the text inside a textbox on another form, so I added a public variable _txt to a form and added an event like so:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    _txt = richTextBox1.Text;
}

But the form is loaded like this:

public FrmTextChild(string text)
{
    InitializeComponent();
    _txt = text;
    richTextBox1.Text = _txt;
    Text = "Untitled.txt";
}

Is there a better way to directly link the two?

+5  A: 

You could use a property instead to read directly from your TextBox. That way you don't need an extra variable at all.

public string Text
{
  get
  {
    return richTextBox1.Text;
  }
}

Add a setter if you also want to be able to change the text.

Michael Madsen
A: 

I don't think you should ever have forms reference each other's controls: when you change the lay out of one you will have to rewrite the code for the other. It is much better IMHO to store shared values in a separate class and have both forms reference that. Like so:

public class DataContainer
{
    public string SomeData{get;set;}
}

public class Form1:Form
{
   private DataContainer _container;
   public Form1(DataContainer container)
   {
      _container=container;
   }

   private void richTextBox1_TextChanged(object sender, EventArgs e) 
   { 
       _container.SomeData = richTextBox1.Text; 
   } 

   private void SpawnForm2()
   {
      var form2=new Form2(_container);
      form2.Show();
}

public class Form2:Form
{
   private DataContainer _container;
   public Form2(DataContainer container)
   {
     _container=container;
   }
}
Dabblernl
A: 

Another way to do it would be setting the Modifiers property for the TextBox (or any other control you want to access) to Protected Internal and then open the second form, the Owner being the first form.

This way, you can later on access the control and its properties with something like this:

((Form1)this.Owner).textBox1.Text = "This is a message from the second form";
Dennis Delimarsky