Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
3.50/5 (4 votes)
See more:
Hello.
I have a user control and a button.
When I click on the button, a new form is opened.

I do it in this way:

C#
protected static MyForm myForm1 = new MyForm();
....

public void buttonClicked()   // called by the button clicked event
{
myForm = new myForm();
myForm.Show();
}


the problem is, that when I click on the button again, another form will be opened.
I want only one form to be able to be opened.

How can I make that?

Thanks
Posted
Comments
Sergey Alexandrovich Kryukov 1-Nov-12 14:59pm    
This is not a problem, this is exactly what you programmed. Want to use the same form? Do it. Where do you see a problem? My advice is simple: stop doing UI, go back and learn some elementary programming on simple samples (with OOP, of course). When you get more confident and come back, your problem will appear simple for you. I'm serious: this advice is better for you then just writing "correct" code...
--SA

You need to do a couple things.
1) Create a local variable holding an instance of the subform in the parent forms class.
var MyFormObj;
2) In your button click handler you create an instance of the form if it doesn't already exist and show it.
If the form already exists then you just show it.
C#
if( MyFormObj == null )
{
   MyFormObj = new myForm();
}
MyFormObj.Show();
 
Share this answer
 
Comments
ruyet7247 30-Jan-21 10:41am    
thanks
Another possibilitiy is to put a static in the MyFormObj and have a variable that is set when form is initialized, and then reset when form is destroyed. Then only create a new instance if the variable is reset.

There is also the Application.OpenForms Property[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Nov-12 22:05pm    
Sorry, this will work, but static should be a last resort. It's more than enough to have an instance member, of, say, main form class. As the main form is used as a singleton, this member will be single, too.
(I did not vote this time, but this is nit a good advice. Doing something which "just works" is not enough.)
--SA
Hi,

This is my solution

C#
public void buttonClicked()   // called by the button clicked event
{
    // looking for opened forms collection
    var _myForm = (MyForm)Application.OpenForms["myForm"];
        if (_myForm == null)
            myForm = new myForm{ name = "myForm"};

    // finally show the form
    _myForm.Show();
}


Hope it will help
Regards
 
Share this answer
 
Comments
Ruggers 18-Apr-18 1:12am    
Perfect..
very simple solution
Jus call ShowDialog() instead of Show().. Done :) :)
 
Share this answer
 
First Disable the button after showing Form:
C#
public void buttonClicked()   // called by the button clicked event
{
    myForm = new myForm();
    myForm.Show();
    (sender as Button).Enabled = false;
}

Then Enable it When the has clothed.

Or Simply use ShowDialog() instead of Show().
 
Share this answer
 
C#
if (Application.OpenForms["My_Form_Name"]!=null)
            {
                //you can use closing or hiding Method
                Application.OpenForms["My_Form_Name"].Close();
             // Application.OpenForms["My_Form_Name"].Hide();
            }
            My_Form_Name frm = new My_Form_Name()
            frm.Show();
 
Share this answer
 
v2
Please refer to my solution in ShowForm():

C#
private void ShowForm(Type typeofForm, string sCaption)
{
    Form fOpen = GetOpenForm(typeofForm);
    Form fNew = fOpen;
    if (fNew == null)
        fNew = (Form)CreateNewInstanceOfType(typeofForm);
    else
        if (fNew.IsDisposed)
            fNew = (Form)CreateNewInstanceOfType(typeofForm);

    if (fOpen == null)
    {
        fNew.Text = sCaption;
        fNew.ControlBox = true;
        fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        fNew.MaximizeBox = false;
        fNew.MinimizeBox = false;
        // for MdiParent
        //if (f1.MdiParent == null)
        //    f1.MdiParent = CProject.mFMain;
        fNew.StartPosition = FormStartPosition.Manual;
        fNew.Left = 0;
        fNew.Top = 0;
        ShowMsg("Ready");
    }
    fNew.Show();
    fNew.Focus();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
    ShowForm(typeof(FAboutBox), "About");
}

private Form GetOpenForm(Type typeofForm)
{
    FormCollection fc = Application.OpenForms;
    foreach (Form f1 in fc)
        if (f1.GetType() == typeofForm)
            return f1;

    return null;
}
private object CreateNewInstanceOfType(Type typeofAny)
{
    return Activator.CreateInstance(typeofAny);
}

public void ShowMsg(string sMsg)
{
    lblStatus.Text = sMsg;
    if (lblStatus.ForeColor != SystemColors.ControlText)
        lblStatus.ForeColor = SystemColors.ControlText;
}
 
Share this answer
 
Hello

I tested the solutions with verifying the from == null condition.
It's working good? But when I close the opened form and i try to reopen it. it's value is not null.

So to resolve this problem i catch the Form Closed event of opened form and i set the null value to my instance:
C#
//Declaration of my form
Form1 _iFrm;

// button code
private void Btn_Click(object sender, EventArgs e)
{
   if (_iFrm == null)
   {
      _iFrm = new Form1 ();
      _iFrm.FormClosed += new FormClosedEventHandler(_iFrm_FormClosed);
      _iFrm.Show(this);
   }
   else
   {
      _iFrm.Activate();
   }
}


// FormClosed event

void _iFrm_FormClosed(object sender, FormClosedEventArgs e)
{
   _iFrm = null;
}


Hope this addition will help some people too!

Thanks
Ed
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900