views:

482

answers:

4

I have an application the will load usercontrols dynamically depending on the user. You will see in the example below that I am casting each user control via switch/case statements. Is there a better way to do this? Reflection? (I must be able to add an event handler Bind in each control.)

override protected void OnInit(EventArgs e)
{
    cc2007.IndividualPageSequenceCollection pages = new IndividualPageSequenceCollection().Load();
    pages.Sort("displayIndex", true);
    foreach (IndividualPageSequence page in pages)
    {
        Control uc = Page.LoadControl(page.PageName);
        View view = new View();
        int viewNumber = Convert.ToInt32(page.DisplayIndex) -1;

        switch(page.PageName)
        {
            case "indStart.ascx":
                IndStart = (indStart) uc;
                IndStart.Bind += new EventHandler(test_handler);
                view.Controls.Add(IndStart);
                MultiView1.Views.AddAt(viewNumber, view);
                break;

            case "indDemographics.ascx":
                IndDemographics = (indDemographics)uc;
                IndDemographics.Bind += new EventHandler(test_handler);
                view.Controls.Add(IndDemographics);
                MultiView1.Views.AddAt(viewNumber, view);
                break;

            case "indAssetSurvey.ascx":
                IndAssetSurvey = (indAssetSurvey)uc;
                IndAssetSurvey.Bind += new EventHandler(test_handler);
                view.Controls.Add(IndAssetSurvey);
                MultiView1.Views.AddAt(viewNumber, view);
                break;
        }

    }
    base.OnInit(e);
}

Thanks in advance!

A: 

You could try TypeOf (in c#) Or would uc.GetType() work.

Brody
+1  A: 
Jeroen Landheer
+1  A: 

I do not see anything control-class-specific in your code. You perform exactly the same operations, and looks like all user controls inherit from Control.

If the only specific thing is the event binding (i.e. Control class does not have Bind event), then better think about refactoring your code, so you make all your user controls to inherit like this: Control -> MyBaseControl(put the event here) -> YouControl.

If you can't control the source of the controls, then Jeroen suggestion should work.

Sunny
+1  A: 

How about defining an interface with a Bind event and have the controls implement it?

public interface IBindable
{
  event EventHandler Bind;
}

Then:

foreach (IndividualPageSequence page in pages)
{
  IBindable uc = Page.LoadControl(page.PageName) as IBindable;
  if( uc != null )
  {
    uc.Bind += new EventHandler(test_handler);
    View view = new View();
    view.Controls.Add(page);
    int viewNumber = Convert.ToInt32(page.DisplayIndex) -1;
    MultiView1.Views.AddAt(viewNumber, view);
  }
}
Andrew Kennan