nscott23 nscott23 - 1 year ago 90
C# Question

how to call function that is in window1 from window2

I have Window1, that has a function that sends

public void proba()


and on a button click it has

Window2 win2= new Window2();
win2.textBoxOne.Text = selectedString;

If from Window2,on a button click I go with code

Window1 win1 = new Window1();

I get a blank messagebox.But if a MessageBox is declared with MessageBox.show("some text"); it works.

This is just a test that I want to get throught.My final idea is to have a method in Window1 that will have the code for sql insert query, with the textboxes from Window1 and I will need that method to be called after a button is clicked on Window2.

Answer Source

You're creating a new instance of Window1:

Window1 win1 = new Window1();

Which means this.comboBoxTipUnosa.Text is empty in that instance.

Instead, pass the existing instance to Window2. First, expect it on the constructor in Window2:

private Window1 window1Instance;

public Window2(Window1 window1)
    this.window1Instance = window1;

Then pass the reference when creating Window2:

Window2 win2 = new Window2(this);

Then in Window2 you can reference the existing instance:


Note: This is a very "WinForms" way of doing things. While I won't claim to be a WPF/MVVM expert, you should definitely put some focus into learning the patterns and practices used in WPF. Treating it like WinForms can "work", but it's clunky and doesn't really make use of the tooling available.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download