Open/Close form on same button
Hey all! I have a problem, which consist of a button that is supposed to open a form, and if i click that button again, the Form should close, and only 1 of this form should be able to run at the time.
Problem is that it keeps opening more forms as i click my button.
[code]
private void button1_Click(object sender, EventArgs e)
{
int on = 1;
int off = 0;
StartMenu StartMenu = new StartMenu();
if (on < off)
{
StartMenu.Dispose();
on = 1;
off = 0;
}
else if(on > off)
{
StartMenu.Show();
off = 1;
on = 0;
}
}
[\code]
This is the code that i attempted to make for the button to register whether the button is active or inactive, and choose if the Form should open or close. :)
Hope you can help!!
Looking into it my code was not readable, i'll try to organize it. :)
Ramalingam SPosted Aug 25, 2009, 3:40 AM
Declare Form1 form = new Form1(); globally
then
private void btnOpenCloseForm_Click(object sender, EventArgs e)
{
if (form.Visible)
form.Hide();
else
form.Show();
}
Kim LarsenPosted Aug 13, 2009, 6:02 AM
Master BillaPosted Aug 13, 2009, 5:23 AM
According your words i have created code to this
private void button2_Click(object sender, EventArgs e)
{
FormCollection frmCollection = Application.OpenForms;
bool IsFormOpened = false;
foreach (Form frmcommon in frmCollection)
{
if (frmcommon.Name == "MyOpenedForn")
{
frmcommon.Close();
IsFormOpened = false;
break;
}
}
if (!IsFormOpened)
{
Form1 frm1 = new Form1();
frm1.Show();
}
}
try that and let me know if you are find any issues.
Thank you