简体   繁体   中英

Calling a method from one form to another show error “Object Reference not set to instance of an object”

I have two forms.When i click a button in Fomr1 after pasting encryption code in textbox,it loads Form2 with asking password and when i click Ok it should close Form2 and it should call a method from From1 without refreshing Form1 (Because am doing decryption in Form1 and if i use new Form1(); it Reloads the Form1 and decryption is not working). Below is my code:

public partial class Form2 : Form
{
    private Form1 form1;
    Form2 form2;
    public Form2()
    {
        InitializeComponent();
    }      
    public bool CheckPwd()
    {
        if (textBox1.Text == "Hi")             
            return true;
        else             
            return false;
    }
    private void ok_Click(object sender, EventArgs e)
    {
        form2 = new Form2();
        //form1 = c

        if (!CheckPwd())
        {
            MessageBox.Show("Password is Incorrect", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            form2.ShowDialog();
            form1.Hide();
            return;
        }
        else
        {               
                MessageBox.Show("Password ok", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();

        }

    }

    private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        form1.Decrypting();  
    }
}

In form1.Decrypting(); i am getting the error "Object reference not set to instance of an object".

First look at this: What is a NullReferenceException, and how do I fix it?

Second object form1 is null in Your Form2 object code You never set the form1 object, that way You get Null error on Form2_FormClosed method

You must set the form1 object for example in form2 ctor

  public Form2(Form1 form1)
        { 
            this.form1 = form1;
            InitializeComponent();
        }  

There are other ways to do this. But may problem is the form1 is no set in form2 code

This is working finally.. In Form2: private Form1 form1;

public Form2(Form1 form1) : this() {

        this.form1 = form1;
    }

In Form1:

form = new Form2(this);

And the method i want to use from From1 to Form2 have to be used as internal void methodname()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM