1

I am having a problem controlling a textbox. I need to change a value from outside of Form1.cs where the textbox is located for this I have found this snippet.

public void UpdateText(string newValue)
{
    torrent_name0.Text = newValue;
}

this allows me in theory to control the textbox outside of Form1.cs, but here comes the problem, every time I want to access it I create a new instance of Form1 instead of using the old one and refreshing it.

Form1 frm = new Form1();
frm.UpdateText("aaaaaaaaaaaa");
frm.Show();

am I missing something? is there a better way to do this? I have tried multiple ways to update the new form but got nowhere.

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
BoKKeR
  • 125
  • 3
  • 14
  • 4
    You should keep a global variable of the first form created and call your method on this reference. – aybe Aug 23 '16 at 20:26
  • [How to Change a Control of a Form from Another Form?](http://stackoverflow.com/questions/38768737/how-to-change-a-control-of-a-form-from-another-form) – Reza Aghaei Aug 23 '16 at 21:11

2 Answers2

1

In that case you can pass the instance of form in the method as argument and make the changes like

public void UpdateText(string newValue, Form1 frm)
{
    frm.torrent_name0.Text = newValue;
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
1

Bokker,

You will have to have a reference to the singular form1 to which all things refer.

If this is a child form, then as Aybe commented, create a public member of your mainform and name it something.

Public Form myForm1;

You probably have some Event by which you would like Form1 be launched...

A Button click, menu item, toolbar item, etc. In that event you will have to check if the form exists and create if required.

private SomeEvent() {
  if (myForm1 == null) 
     {
      myForm1 = new Form1();
      myForm1.Show(this);
     }

  myForm1.UpdateText("some text");

}

Alternatively, you could create the form in the Form Load event, just so long as you create the form prior to attempting the myForm1.UpdateText() If you follow this paradigm, you are creating myForm1 as part of the main form, best practice says you should also dispose of the form in your main form Closing Event.

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
  {
     if (myForm1 != null) 
       {
         myForm1.Close();
         myForm1.Dispose();
        }
  }

This is all off the top of my head, so it might not be perfect.

Marc Lyon
  • 336
  • 2
  • 7
  • This works in the Form1.cs but in the other cs file myForm1 is unrecognized, could you tell me how to include it ? I am googling around and not much luck so far, thanks – BoKKeR Aug 24 '16 at 16:54
  • 1
    You may have to move the definition of form1 upwards. You may have to make it a public member of your main program or Application object (if you have one). If moved to your main program (assuming its called Program) you would have to reference the form with Program.Myform1. – Marc Lyon Aug 30 '16 at 18:12