0

I need some help please. I made a lot of research, but i didn't find any answers that apply for me.

Considere 2 forms : MainWindow and Form2. MainWindow contains a textbox, and some labels which displays informations. Form2 contains also a textbox, but is designed to perform time consuming tasks. In this form2 I want to pass the value of a selectedItem (a string), to my MainWindow textbox, and run a method on it.

I am able to do this by loading or opening a new MainWindow, but I don't want to do that. Both forms can be (and will be) opened at the same time.

How can I do this please ? Let me know if i am not precise.

tobre
  • 1,347
  • 3
  • 21
  • 53
Rems
  • 119
  • 8
  • This is partly related to [this](https://stackoverflow.com/questions/18366729/access-an-existing-main-winform-instance-from-any-child-form) question. But if your method is time consuming you may not run it on the UI thread, but use something like tasks, depending on the ui framework you're using. – Pretasoc Jan 08 '19 at 08:30
  • If I understand you correctly, your Form2 needs a reference to the MainWindow and the MainWindow needs a functionality/ property to pass the value to (from Form2) – royalTS Jan 08 '19 at 08:31
  • Is it a web project or desktop ? If web project then declare a global variable inside your common.js file. – mgsdew Jan 08 '19 at 08:32
  • I guess I misexplained my issue. It's a desktop application. What I need to do is finally pretty simple in a few words : update a textbox.text from a form to another form, which both are opnened at the same time. – Rems Jan 08 '19 at 08:48

3 Answers3

0

In MainWindow :

private void button1_Click_1(object sender, EventArgs e)
{
    var f = new Form2();
    f.Owner = this;
    f.ShowDialog(/*this*/);
}

In Form2

(this.Owner as MainWindow).Text = textBox1.Text;

Or call :

(this.Owner as MainWindow).DoSomething();
CodeMan
  • 671
  • 6
  • 13
  • Unfortunally, it doesn't works. Firstly, Showdialog don't accept argument :( Secondly, in Form2, it returns me a NullReferenceException. – Rems Jan 08 '19 at 09:22
0

If you only have one MainWindow you can just make a static link to the instance of your MainWindow

MainWindow

    public static MainWindow Instance { get; private set; }

    public MainWindow()
    {
        InitializeComponent();

        Instance = this;
    }

Form2

    if ( MainWindow.Instance != null )
            MainWindow.Instance.textBox1.Text = "Hello";

Of course this will probably only worked if they are opened in the same thread.

pm101
  • 1,309
  • 10
  • 30
0

I finally find how to do this.

I followed a video tutorial which apply perfectly to my issue : https://www.youtube.com/watch?v=Tu07ubhxyfY

After a little tweak, it works fine.

Thank's a lot for answers.

Rems
  • 119
  • 8