【问题标题】:Close this and send values to parent(Main) window关闭它并将值发送到父(主)窗口
【发布时间】:2023-01-18 05:12:53
【问题描述】:

大家好,

我用这个但是我得到一个错误。

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

    }

谁能告诉我为什么这不起作用? 先感谢您。

【问题讨论】:

  • 这回答了你的问题了吗? What is a NullReferenceException, and how do I fix it?
  • 你这样做是错的。对话框不必关心调用表单。只需通过属性公开数据 - 如果合适,只读属性 - 然后调用表单可以获取数据并在 ShowDialog 返回后根据需要使用它。
  • 如果您按照我上面的说明进行操作,那么这将是无关紧要的,但是,关于您提出的具体问题,您首先是如何显示对话的?我怀疑你实际上并没有设置Owner,在这种情况下,从它那里得到除了null之外的任何东西都是没有意义的。

标签: c# windows winforms


【解决方案1】:

从错误看来,来自 thisTxtName.Text,TxtCode.Text,TxtPrice.Text,TxtMt.Text,TxtQty.Text,MyTotal 的内容似乎为空。如果您使用 Visual Studio(代码或任何版本的 VS),我建议您使用断点,然后您将能够看到到底什么是 null。无论如何,你也可以像这样在你的类中创建一个可以为空的文件:public string Text{ get; set; } => public string? Text{ get; set; }

【讨论】:

  • 这似乎不太可能。在当前表格中,它们可能都是TextBoxes,因此不可能是null。我想它更有可能是 frm1 那是 null,但无论如何都不需要。
  • 哦,我认为你是对的,我的错。问题是我不是 WPF 专家,但我想我的一般建议应该有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
相关资源
最近更新 更多