views:

110

answers:

1

I have a .NET CF program (running on a Smartphone) and I have written an options page for it.

On the options page I have links to 6 other forms which contain the actual options. When the main form loads it creates the 6 subforms and stores them in a list ready to be launched. The issue with this is the initial creation time required to make these forms, which makes the main settings form slow.

What I would ideally like, is a way to just specify the type and parameters required to create the subform on load, then actually create the form when needed.

Here is code snippets of how it currently works:

Form_OnLoad():

AddSettingsOptions("General", new General());
AddSettingsOptions("Action Alert", new BaseAlertForm("Action Alert Settings", SystemManager.ActionAlert));
AddSettingsOptions("Comms Alert", new BaseAlertForm("Comms Alert Settings", SystemManager.CommsErrorAlert));
AddSettingsOptions("Advanced", new Advanced());
AddSettingsOptions("Diagnostics", new Diagnostics(_unitWatcher));
AddSettingsOptions("About", new About());

The form is stored in the Tag section of a list (which displays the sub options)

private void AddSettingsOptions(String name, Form form)
{
    listViewSettings.Items.Add(
        new ListViewItem(
            String.Format(" {0}   {1}", listViewSettings.Items.Count + 1, name))
            {
                Tag = form
            }
        );
}

If an option is pressed the following function is called to launch the form

private void ShowSubSetting(ListViewItem item)
{
    if (item == null)
        return;

    object tag = item.Tag;
    Form form = tag as Form;
    if (form != null)
    {
        form.ShowDialog();
        //form.Dispose();
    }
}

I'm sure there is a pretty easy way to do this, I'm just struggling with the correct way. Thanks

+2  A: 

You can do it this way:

AddSettingsOptions("General", ()=> new General() );
AddSettingsOptions("Action Alert", ()=> new BaseAlertForm("Action Alert Settings", SystemManager.ActionAlert) );
// etc ...

void ShowSubSettings(ListViewItem item ){
   if ( null == item ) { continue; }

   object tag = item.Tag;
   Func<Form> func = tag as Func<Form>;
   if ( null != func ) {
      Form frm = func();
      if ( null != frm ) {
          frm.ShowDialog();
      }
   }
}

If you are using C# 2.0, you must use

delegate { return new General(); }

instead of

()=> new General();
TcKs
Thanks that looks like a good way; I cannot get it to work just yet though, I get the error: "Only assignment, call, increment, decrement, and new object expressions can be used as a statement" on lines using (Func<Form>)
Chris
Seems to work without the (Func<Form>) - thanks
Chris
I've wrote that from scratch without compiling. I removed (Func<Form>) from the answwer.
TcKs