Questions & Answers

Close this and send values to parent(Main) window

Hello all,

I use this but i get an error.

   private void button1_Click(object sender, EventArgs e)
        // When i use this,
        // -------------------------
        // Form1 frm1 = new Form1();
        // frm1.ShowDialog();
        // -------------------------
        // This works for sure...
        // But i don't wanna open that already open form one more time.
        // So i use as u see it below.

        Form1 frm1 = (Form1)this.Owner;
        int MyTotal, a, b;
        a = Convert.ToInt32(TxtPrice.Text);
        b = Convert.ToInt32(TxtQty.Text);
        MyTotal = a * b;

        // But i get error and it says:
        // System.NullReferenceException: 'Object reference not set to an instance of an object.'


anybody can tell me why this doesn't work ? Thank you in advance.

2023-01-18 00:00:02
2023-01-18 00:00:02
You're doing it wrong. The dialog doesn't have to care about the calling form. Just expose the data via properties - read-only properties if appropriate - and then the calling form can get the data and use it as required after ShowDialog returns.
2023-01-18 00:00:03
If you follow my instructions above then it will be irrelevant but, with regards to the specific issue you raised, how EXACTLY did you display the dialogue in the first place? I suspect that you didn't actually set the Owner, in which case getting anything but null back from it would make no sense.
Answers(1) :

From the error It seems like something from thisTxtName.Text,TxtCode.Text,TxtPrice.Text,TxtMt.Text,TxtQty.Text,MyTotal is null. I recommend you to use breakpoint if you use Visual Studio (Code or any version of VS) and then you will able to see what exactly is null. Anyway, you also can make a filed in your class nullable like this: public string Text{ get; set; } => public string? Text{ get; set; }

2023-01-18 00:00:03
That seems unlikely. They are all presumably TextBoxes on the current form, so none are likely to be null. I fancy it's more likely to be frm1 that's null, but that shouldn't be required anyway.
2023-01-18 00:00:03
Oh, I think you're right, my bad. The problem is I am not WPF expert, but I suppose my recommendation in general should help.