How to create and dispose the same object? I have created a form with button, on button click even I create a object and by clicking on same button I dispose the object! I m able to create a object but not able to dispose the same object. How to do it?

private void mouseClkbtn_Click(object sender, EventArgs e)
        {
            Project1.Form1 prjform = new Project1.Form1();

                if (mouseClkbtn.Text == "Latch Enable")
                {
                   
                    prjform.Show();
                    mouseClkbtn.Text = "Latch Disable";
                }
                else if (mouseClkbtn.Text == "Latch Disable")
                {

                    prjform.Hide();
                    prjform.Dispose();
                    mouseClkbtn.Text = "Latch Enable";

                }

            
        }

What is wrong with my code?

Recommended Answers

All 3 Replies

You need the reference to prjform to be global in the class calling the mouse click method.

Example:

Project1.Form1 prjform = null;

private void mouseClkbtn_Click(object sender, EventArgs e)
{
  if (btnLatch.Text == "Latch Enable") // might be safer to use if (prjform == null) instead
  {
    prjform = new Project1.Form1();
    prjform.Show();
    btnLatch.Text = "Latch Disable";
  }
  else
  {
    prjform.Close(); // close calls hide and dispose
    prjform = null; // dereference here
    btnLatch.Text = "Latch Enable";
  }
}

When you call Dispose() method on some object, it means it is completey shuted down (you can understand it to be more then Closed - while closed object you can still access to it with its reference).
So Disposed objects are like then is no reference to them (not exisitng anyhow, and anylonger).

Concerning your example, your reference of a class must be an the class level, not on event level (now you create a new reference of the new form every time you click on the button).

Look at darkagn example, but you can still do it like:
Project1.Form1 prjform = new Project1.Form1(); //on class level you instanitate reference of a form (it will be done jsut before form load

private void mouseClkbtn_Click(object sender, EventArgs e)
        {
              if (mouseClkbtn.Text == "Latch Enable")
                {                   
                    prjform.Show();
                    mouseClkbtn.Text = "Latch Disable";
                }
                else if (mouseClkbtn.Text == "Latch Disable")
                {
                    prjform.Hide();
                    prjform.Dispose();
                    mouseClkbtn.Text = "Latch Enable";
                }            
        }

Thanks darkagn for example and mitja for explaining!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.