Binding a text field to a variable?

I would like to have direct access to the text inside the text box in a different form, so I added the public variable _txt to the form and added an event like this:

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

But the form loads as follows:

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

Is there a better way to directly link the two?

+3
source share
3 answers

Instead, you can use the property to read directly from your TextBox. This way you don't need an extra variable at all.

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

Add an installer if you also want to change the text.

+6
source

, - : , . . :

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;
   }
}
+2

Another way to do this is to set 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 will be the first form.

That way, you can later access the control and its properties like this:

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

Source: https://habr.com/ru/post/1738865/


All Articles