Click here to Skip to main content
15,909,324 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
m working on an windows application form(FormA) that has a button,upon button_click event i want another windows form(FormB) instantiated,which is a seperate winform from the main winform (FormA).i want to instantiate the newly instantiated winform(FormB) to have only a single instance,upon button click event it should not create another winform(FormB).is there a way to do this other than using singleton pattern for FormB??Expecting logical approach as answers...Pls give some options..

What I have tried:

expecting efficient approaches..
Posted
Updated 23-Feb-17 9:36am
Comments
[no name] 23-Feb-17 14:37pm    
Disable the button that creates the other form. Check the the forms collection to see if there is an existing instance for the form, if there is, do not create a new one. The big question is, what have you tried?
Maciej Los 23-Feb-17 14:55pm    
It can't be so easy! :laugh
[no name] 23-Feb-17 15:08pm    
Well the easy way is to post a "question" on CP and hope someone does your work for you.
rajkiran.07 23-Feb-17 15:30pm    
wasnt expecting C# code for my query, an approach that could point me to a direction would have been helpful..
[no name] 23-Feb-17 15:37pm    
And that is exactly what you got.

1 solution

As NotPoliticallyCorrect mentioned, if the form is open, the button should be disabled.

But to answer your question, the following code does what you ask:
C#
private void ButtonClick(object sender, EventArgs e)
{
    Form form = null;
    if (sender == button1)
    {
        if (Application.OpenForms[nameof(Form1)] == null)
            form = new Form1();
    }
    else // button2
    {
        if (Application.OpenForms[nameof(Form2)] == null)
            form = new Form2();
    }
    if (form != null)
    {
        form.Owner = this;
        form.Show();
    }
}
 
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