Deepanshu Mishra
Deepanshu Mishra

Reputation: 303

Trouble in Passing Value from one Window to Other in WPF C#

I am not able to understand what's wrong going in with my code.

Two Windows (window1 , window2 )

I have a button(button1) and a textBox(textBox1) on window1 and another button(button2) and a textBox(textBox2) on window2

WHAT I WANT:

is when I press button1, window2 will open as a dialogueBox, then whatever I write in textBox2 and press button2 should redirect to window1 with my text in textBox1.

PROBLEM:

is when I click button2, there is no transfer of data to textbox1, It remains Empty.

MY CODE:

public partial class window1: Window
{
    public Window1()
    {
        InitializeComponent();
        textbox.text=cd;
    }

    private string cd;
    public string getCode
    {
        get { return cd; }
        set { cd = value; }

    }


    private void button_Click_1(object sender, RoutedEventArgs e)
    {
        Window2 win2 = new Window2();

        this.Close();
        win2.ShowDialog();
    }

}

and this is other window:

public partial class Window2 : Window
{


    private void button_Click(object sender, RoutedEventArgs e)
    {
        Window1 win1 = new Window1();
        win1.getCode = textBox.Text;
        this.Close();
    }
}

Any Suggestion would be much appreciated.!

Upvotes: 1

Views: 260

Answers (2)

Parrish
Parrish

Reputation: 177

Anton has the answer. If you want another way you can make the first window the owner of the second so now the owner can be reference back. I was going to write out some code but remember a post a while back showing it and found it. Check it out. How to manipulate a window object from another class in WPF

Upvotes: 2

Anton Danylov
Anton Danylov

Reputation: 1491

You need to pass reference to Window1 to child window:

private void button_Click_1(object sender, RoutedEventArgs e)
{
    Window2 win2 = new Window2();
    win2.Wnd1Reference = this;

    this.Visibility = Visibility.Collapsed;
    win2.ShowDialog();
}

public partial class Window2 : Window
{
    public Window1 Wnd1Reference {get; set;}

    private void button_Click(object sender, RoutedEventArgs e)
    {
        Wnd1Reference.getCode = textBox.Text;
        this.Close();
        Wnd1Reference.Visibility = Visibility.Visible;
    }
}

Upvotes: 1

Related Questions