1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

show/create form from variable

Discussion in 'C#' started by Rhuntsman21, Sep 8, 2010.

  1. Rhuntsman21

    Rhuntsman21 New Member

    Joined:
    Sep 8, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I am still learning C# so I am sorry if I do not use the correct terminology.

    Here is what I am trying to do. I have the following code that I use to check to see if an instance of a form already exists, and if it does show it. Otherwise it creates the form and then shows it.
    Code:
     private void btnAdd_Click(object sender, EventArgs e)
            {
                if (chbDetail.Checked == true)
                {
                    bool exists = false;
    
                    foreach (Form f in Application.OpenForms)
                    {
                        if (object.ReferenceEquals(f.GetType(), typeof(Ingredient)))
                        {
                            exists = true;
                            break;
                        }
                    }
    
                    if (exists)
                    {
                        Ingredient ingredient = (Ingredient)Application.OpenForms["Ingredient"];
                        ingredient.Show();
                    }
                    else
                    {
                        Ingredient ingredient = new Ingredient();
                        ingredient.Show();
                    }
                }
            }
    
    The problem is that I need to do this with multiple forms in different parts of my program, so I wanted to create a class that I could just pass a variable into and have it open any form I wanted. I thought about using a switch but then I am still writing the code out multiple times. Any ideas would be appreciated.
     

Share This Page