Arsalan Khattak
Arsalan Khattak

Reputation: 958

String set to null

I have two Windows namely MainWindows and Form2 . On pressing a Button on MainWindows, Form2 appears . In the second Window I have two textboxes and I added strings to store whatever is in these textboxes when I click the Button of Form2 but they set to null instead of storing the values.

private void remove_Button_Click(object sender, RoutedEventArgs e)          
 {           
    string userValue;

    userValue = user_Text.Text;
    form2 form = new form2();
    form.Show();
    form.Replace_Button.Click += Replace_Button_Click;

  }

  void Replace_Button_Click(object sender, RoutedEventArgs e)
  {
    form2 form = new form2();
    replaceFirstValue = form.firstValue_TextBox.Text;
    replaceLastValue = form.lastValue_TextBox.Text;
    repFirstConversion = int.TryParse(replaceFirstValue, out repFirstInt);
    repLastConversion = int.TryParse(replaceLastValue, out repLastInt);
    if (repFirstConversion == false)
         this.Close();
              //MessageBox.Show("Please Enter Integer");                       
    }

I don't have any code in form2.xaml.cs .

Upvotes: 1

Views: 101

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31153

You create a new instance of form2 in both event handlers, therefore you have two different forms. The latter knows nothing about the former and will only have default values.

You have to only create one instance of form2 and store a reference to it in a member variable and then use that to retrieve the values.

private form2 form; // A member variable to hold a reference to the form

private void remove_Button_Click(object sender, RoutedEventArgs e)
{
    ...
    form = new form2(); // Set the member variable
}

And from Replace_Button_Click remove the first line where you created a new instance of form2.

Upvotes: 2

Related Questions