views:

1212

answers:

3

In a C#, Windows forms app, we have a series of user controls that are associated with menu entry records in a database...

    ID  Menu Title
    1   User Management
    4   Group Management
    6   System Utilities
    12  Configuration Management

A few user controls...

  • UserManagement.cs
  • GroupManager.cs
  • SysUtil.cs
  • ConfigurationMan.cs

We're currently just switching on the ID, but that seems like a very primitive way to accomplish this and has a lot of hard-coded IDs, which I don't like.

What would be the most appropriate way to read the database entries and load the appropriate user control?

Thanks!

+1  A: 

You could store the class names in the database and instance them via reflection. They would need to all implement an interface or all derive from a base class (which I'm assuming you're doing, extending Control) in order to be dealt with without having to handle each individual class differently.

Welbog
Thanks! I thought this might be the case, but wanted to check.
80bower
A: 

In some ways, the switch (perhaps on an enum rather than just an id) is quite reasonable. You could push the assembly-qualified names into the DB, but what does the DB care about assemblies or classes? And what happens when you refactor? Move to java? Need to support multiple UI engines? Nah, I'd probably just switch myself - in a factory method to encapsulate it...

public static Control CreateControl(ControlType controlType) {
    switch(controlType) {
        case ControlType.Foo:
            return new blah...
        case ControlType.Bar:
            ...
    }
    throw new ArgumentOutOfRangeException();
}
Marc Gravell
A: 

You could probably store the type name in the database and use reflection to new up your user controls.

Dan