Building a form navigation class

Using a form navigation class is a good approach to UI navigation in any application. By placing the code to launch a form in a single location, changes to the form in the future will be an easier task.

For instance, consider the following code to launch the AccountViewer form:

public void btnLaunch_Click(System.Object sender, System.EventArgs e)
{
AccountViewer _accountViewer;
_accountViewer = new AccountViewer ();
_accountViewer.ShowDialog ();
_accountViewer.Dispose();
_accountViewer=null;
}

Suppose your boss asked you to replace the AccountViewer form with an entirely different form. You would have to go through your code to look for the preceding code to make your change. Now imagine if you did the same thing in twenty different places. Making such a change would be a messy affair. If you centralize form navigation, launching the form would be possible in a single call to the navigation service, passing in a tag to indicate which form you wish to display:

public void btnLaunch_Click(System.Object sender, System.EventArgs e)
{
NavigationService.ShowDialog("AccountViewer");
}

The actual form objects used would be transparent to the rest of your application. To implement the change your boss requested, all you would need to do is to switch the form objects associated with the AccountViewer tag in the NavigationService class.

Let's add the NavigationService class to your project now. The ShowDialog() function takes in the name of the form that you wish to display as well as an argument (if available) to supply to the instantiated form object. We can launch the forms that correspond to the specified name using a switch.case statement. In the following code, we launch the PluginsSetup form you've created in Chapter 2 when the SetupDatasources tag is specified.

using System.Windows.Forms;
namespace CRMLive
{
public class NavigationService
{
public static DialogResult ShowDialog(string DialogName, object Arg1)
{
DialogResult _dialogResult = DialogResult.Cancel;
switch (DialogName)
{
case "SetupDatasources":
PluginsSetup _PluginsSetup = new PluginsSetup();
_dialogResult = _PluginsSetup.ShowDialog();
_PluginsSetup.Close();
_PluginsSetup.Dispose();
_PluginsSetup = null;
break;
}
return _dialogResult;
}
}
}

The fact that it is declared as a static method allows you to call this method from anywhere without having to specifically instantiate the NavigationService class.

That's all there is to it! You now have a form navigation class. We will add the ability to launch other forms as we proceed further in this chapter. Now let's take a look at how we can create the main menu for the application and launch it using the NavigationService class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.173.227