0

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;
        frm1.dataGridView1.Rows.Add(TxtName.Text,TxtCode.Text,TxtPrice.Text,TxtMt.Text,TxtQty.Text,MyTotal);
        this.Close();

        // 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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – John Aug 18 '22 at 11:00
  • 1
    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. – John Aug 18 '22 at 11:04
  • 1
    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. – John Aug 18 '22 at 11:07

1 Answers1

0

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; }

  • 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. – John Aug 18 '22 at 11:09
  • 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. – Ilya Chudinovskikh Aug 18 '22 at 11:28