Emad Hamed
Emad Hamed

Reputation: 11

C# WPF I cannot get value of textbox in Mainwindo.xaml.cs in onther class

Simply, I am trying to get value in textbox to use it in other class, but it comes in other class empty.

Can you help me please?

This simple code is in mainform:

    namespace WpfApplication4

    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            public string  GetTxt
            {
                get { return textBox.Text; }
                //set { };
            }

            private void button_Click(object sender, RoutedEventArgs e)
            {
                Class1 cls = new Class1();
                cls.txt();

            }
        }
    }
     and this code in class:
    namespace WpfApplication4
    {
        public class Class1
        {
            MainWindow mw = new MainWindow();
            public void txt()
            {
                System.Windows.MessageBox.Show(mw.GetTxt);
            }

        }
    }

So, can you help me please?

Upvotes: 1

Views: 516

Answers (2)

wingerse
wingerse

Reputation: 3796

Well, you see the line MainWindow mw = new MainWindow();. This creates a new MainWindow object and the default value for its textBox.Text is apparently "".
To solve this, you can make the constructor of Class1 accept a string. And it will also need a string field so that it can be used by txt method. So add this constructor to your Class1:

public Class1(string text){
    _text = text;
}

Add this line in the class to add the field : private string _text;. Now change your txt method like this:

public void txt()
{
    System.Windows.MessageBox.Show(_text);
}

It's all setup now. In the button_Click in your MainWindow class, change your class declaration as follows:

Class1 cls = new Class1(textBox.Text);

Or simple, as William suggested, you can have your txt class have a string parameter as well. But if you want to use the textbox value in more than 1 method, you want to store it in a field. Else you can just make your method accept it as a parameter.

Upvotes: 1

Clay Ver Valen
Clay Ver Valen

Reputation: 1073

When the button is clicked in MainWindow, it creates a new instance of Class1, which creates a NEW MainWindow. In this new instance of MainWindow, textbox.Text is empty. You need to call GetText on the existing instance (the one where the button was clicked).

Upvotes: 0

Related Questions