Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data between WPF forms

Tags:

c#

button

wpf

form1 has a button btnInvoke which invokes form2. form2 contains a textbox and a button btn2.

The user has to enter data in textbox and press btn2.

When btn2 is clicked form2 has to send textbox data to form1.

I have tried passing through constructors but I cant initiate a new instance of form1.

What shall I do?

like image 539
Vasanth91 Avatar asked Jul 09 '26 08:07

Vasanth91


1 Answers

There are two methods that you can use. The first of which would be using ShowDialog and a public method then testing that the DialogResult is true then reading the value from the method.

i.e.

if (newWindow.ShowDialog() == true)
            this.Title = newWindow.myText();

The second method would be to create a CustomEvent and subscribe to it in the creating window like this.

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Window1 newWindow = new Window1();
        newWindow.RaiseCustomEvent += new EventHandler<CustomEventArgs>(newWindow_RaiseCustomEvent);
        newWindow.Show();

    }

    void newWindow_RaiseCustomEvent(object sender, CustomEventArgs e)
    {
        this.Title = e.Message;
    }
}

Window1.xaml.cs

public partial class Window1 : Window
{
    public event EventHandler<CustomEventArgs> RaiseCustomEvent;

    public Window1()
    {
        InitializeComponent();
    }
    public string myText()
    {
        return textBox1.Text;
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {

        RaiseCustomEvent(this, new CustomEventArgs(textBox1.Text));
    }
}
public class CustomEventArgs : EventArgs
{
    public CustomEventArgs(string s)
    {
        msg = s;
    }
    private string msg;
    public string Message
    {
        get { return msg; }
    }
}
like image 172
Mark Hall Avatar answered Jul 12 '26 02:07

Mark Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!