The code you tried will never work. You create a
new object
of
frmCustomer
and close it before ever opening it. You must understand that when you apply
new
you create a completely
new object
. This
object
is of the same
class
of an earlier created
object
but the data is not the same. Therefore you cannot control the other
object
s of the same
class
by simply using another instance of that
object
.
To close this
Form
you would need the actual reference to that
Form
. So you would need to give this to your
frmInventory
(you could for example add a property where you can set this reference) and use that to close the other
Form
.
Another way is to look for that
Form
in all open
Form
s of your
Application
like this:
for (int index = Application.OpenForms.Count-1; index>= 0; index--)
{
if (Application.OpenForms[1].Name == "Customer")
{
Application.OpenForms[1].Close;
}
}
Be aware that using a
foreach
like this can result in an
Exception
:
foreach (Form form in Application.OpenForms)
{
}
This is because you altered the list within the loop which might give you an invalid operation exception.
Good luck!