Jim Rogers

Lives in Baton Rouge, LA, with two dogs, one cat, and one lovely wife. I'm a lead developer for GCR Incorporated.

Katrin and Jim

Month List

Programmatically Adding a User Control in ASP.NET

by jim May 24, 2012 3:49 PM

At first, this appears to work (don’t do this!)

<% If Me.Voter.VoterType <> Voter.VoterLoginType.Parish Then%>
    <uc:BallotByVoter ID="bcVoter" runat="server" />
<%Else%>
    <uc:BallotByRegion ID="bcRegion" runat="server" />            
<%End If%>

The drawback to this technique is that both controls are created and run through the page lifecycle – at least up to the Page_Load.  This may not be desirable if they hit the database to populate dropdowns, or perform other tasks when loaded.

The solution to this is create a placeholder on the page:

<asp:PlaceHolder runat="server" ID="plhChooser"></asp:PlaceHolder>

And programmatically load the controls and place them on the form:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim chooser As Control
    If Me.Voter.VoterType <> Voter.VoterLoginType.Parish Then
        chooser = LoadControl("BallotByVoter.ascx")
    Else
        chooser = LoadControl("BallotByRegion.ascx")
    End If
    AddHandler CType(chooser, BallotChooser).BallotChosen, AddressOf BallotChosen
    plhChooser.Controls.Add(chooser)
End Sub

This works fine for me with pre-populated dropdowns, and across postbacks. Note the use of LoadControl(), rather than just new-ing up the controls; this parses the file and creates the controls within your user control.

Tags:

Code