Click here to Skip to main content
Licence CPOL
First Posted 2 Nov 2008
Views 9,242
Downloads 57
Bookmarked 16 times

Open Forms Elegantly

By | 2 Nov 2008 | Article
This article will show an elegant way to open a lot of forms, without the redundant code

Introduction

This article will introduce a way to reduce the code that is used to open various forms from an applications main menu.

The Problem

As with most Windows applications, the main form will mainly be used to open a lot of other different forms, depending on the application's purpose.

The usual way would be to handle the button's "Click" event, and to instantiate an instance of the form, and to "ShowDialog".

When the application needs to open a lot of forms, these "Click" events for each button could cause the code to become very messy quickly.

I therefore set out to try and find an easier way to reduce the code needed to open all the different forms.

In the sections below, I will explain the solution I came up with.

The Solution

Every component has a "Tag" property that takes an Object as value. This means that we can save any value we want in it.

For the proposed solution, we will make use of this Tag property to save the name of the form we want to open. For example, if we want a button to launch a form named "frmTest", we use the designer properties to set the Tag property to "frmTest". Take note: the name of the form is NOT the value in the "Text" property, it is the value in the "Name" property.

We have only ONE method that will take care of launching all the various forms.

The LaunchForm method is the method we link to the Click event of the button. This can easily be done with the designer properties. Because we need to link this method to the button's Click event, we need to specify the two parameters required. The parameters are:

  • sender of type object, which is the control that the Click event belongs to
  • e of type EventArgs, which is the event arguments associated with the Click event
/// <summary>
/// Method is used to launch an instance of a desired Form. 
/// Link to the Click event of the objects.
/// </summary>
/// <param name="sender">Object used to launch the Form.</param>
/// <param name="e">Event arguments</param>
internal void LaunchForm(object sender, EventArgs e)
{
    //Set the default value to empty
    String FormName = String.Empty;
    try
    {
        //Cast the sender to the appropriate type
        ToolStripMenuItem item = sender as ToolStripMenuItem;

        //A form name consists of the namespace, as well as the type.
        //To get the namespace dynamically, we use a bit of reflection
        //Assembly.GetExecutingAssembly().FullName returns the fullname 
        //of this assembly.
        //We then use the Split function to obtain only the namespace
        //(The first part returned in the string array.
        //We then combine the returned namespace with the FormName
        //specified in the Tag property of the ToolStripMenuItem.
        FormName = Assembly.GetExecutingAssembly().FullName.Split(',')[0] +
        			"." + item.Tag.ToString(); ;

        //Use the string representation of the FormName to obtain the 
        //actual type to instantiate.
        Type uiType = Assembly.GetExecutingAssembly().GetType(FormName);

        using (Form form = Activator.CreateInstance(uiType) as Form)
        {
            //Now we have an instance of the form, 
            //and can modify the properties to suit our need
            form.StartPosition = FormStartPosition.CenterScreen;

            form.Text = "Demo - " + item.Text;

            //Set the Icon of the Form to that of the Image used on the MenuItem
            form.Icon = GetIconFromImage(item.Image);

            //Show the Form.
            form.ShowDialog();
        }
    }
    catch (Exception ex)
    {
        //Do some proper exception handling here
        MessageBox.Show(String.Format
        	("Error opening window: {0}. Error Message: {1}", FormName, ex.Message));
    }
}

A form's full name consists of the name of the form, as well as the namespace in which it resides.

If we look at the code, we can see that with a little bit of reflection we can easily obtain the namespace of the form, and by combining it with the name specified in the Tag property.

Once we have an instance of the Form we want, we are free to do all sorts of manipulations to the forms we want to launch. In the sample code above, we set the StartPosition. We also use the sender parameter to determine the type of control used to launch the form. By doing this, we can access the Text, as well as other properties such as the image, etc….

By launching the forms in this way, the code is in one centralised location, which makes maintaining it very easy!

Below is a screenshot of which properties must be set. The screenshot is of a ToolStripMenuItem that opens a form called "frmTest". As you can see, the Tag property is set to "frmTest", and the Click event is set to call "LaunchForm". That's all you need!

Image of properties to set.

Please let me know what you think, and if you found this code useful! I welcome any feedback!

History

  • 31st October, 2008 - Initial version

License

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

About the Author

Dieter Deysel

Software Developer
South African Reserve Bank
South Africa South Africa

Member

I am currently employed by the South African Reserve Bank where my main focus is Windows Application Development in C#.
 
I enjoy experimenting with new technologies, reading, watching movies and relaxing with friends.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralWhile trying to open MDI child - Child opens and then closes immediately PinmemberTushar Bhatt23:10 5 Jan '09  
GeneralPerhaps a better way to get the Namespace PinmemberIlíon1:20 7 Nov '08  
GeneralLoading menu items in runtime Pinmemberbeatles169223:20 3 Nov '08  
GeneralFeedback PinmemberDieter Deysel21:13 3 Nov '08  
Generalhmmm. Pinmemberjohannesnestler3:57 3 Nov '08  
GeneralNot so nice, really Pinmemberjuggler2:17 3 Nov '08  
GeneralNice..But PinmemberBAIJUMAX18:11 2 Nov '08  
GeneralRe: Nice..But PinmemberItay Sagui21:49 2 Nov '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 2 Nov 2008
Article Copyright 2008 by Dieter Deysel
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid