0

When a button is clicked in Dialog window, the program must run Test() which is defined in the Main window.

Main

namespace Program
{
    public partial class Main : Form
    {
        private __Dialog _Dialog = null;
        public Main()
        {
            InitializeComponent();
            using (this._Dialog = new __Dialog())
            {
                _Dialog.ShowDialog(this);
            }
        }
        public void Test()
        {
            //
        }
    }
}

Dialog

namespace Program
{
    public partial class __Dialog : Form
    {
        public Main p;
        public __Dialog()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, EventArgs e)
        {
            p.Test();
        }
    }
}


I get this error message:


NullReferenceException was unhandled

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe

System.NullReferenceException {"Object reference not set to an instance of an object."}


What can be done to fix it?

Community
  • 1
  • 1
acoder
  • 667
  • 2
  • 9
  • 19
  • 2
    You forgot to pass an instance of the main form to the other form. Take a look at this post:[Interaction between forms — How to change a control of a form from](https://stackoverflow.com/questions/38768737/interaction-between-forms-how-to-change-a-control-of-a-form-from-another-form). *Example 4 - Create public Method or Property in first Form and pass an instance of First Form to constructor of second Form* is what you need. – Reza Aghaei Oct 10 '16 at 15:29
  • 1
    Huh? You just defined `p`, you didn't actually tell `__Dialog` that p was *equal* to anything. So of course you're going to get a NullReferenceException... – neminem Oct 10 '16 at 15:29

0 Answers0