Tuesday, November 29, 2011

Dynamically Changing Master Pages and their contents

Some times we may need to use different master pages for may be different users. To have this capability you need to have more than one master page inside your website first, and control which master page to display inside the code behind but you should select a default master page for each web form.

Suppose you have two different master pages one for students and the other for web administrator.
To change the master page of a web form you need to add this event to your code behind file




Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs)    Handles Me.PreInit
        If Request.QueryString("userName") = "Ahmed" Then
            Me.MasterPageFile = "~/MasterPage2.master"
        End If
    End Sub

Here I am changing the masterpagefile of the current web form iside its code file. I am using query string to identify which user logged in but this may not be the case when we manage users. We shall see this topic in the following chapters.

Also you can manage the contents inside the masterpage without the need to change the master page. So we need to access the controls inside the master page directly inside the content page to do this you should use the property Master ( which is an object) of the current page. Within that object we have the FindControl() method. See this example which changes the banner image displayed inside the masterpage:


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim IMG As Image = CType(Master.FindControl("Image1"), Image)
        IMG.ImageUrl = "~/RememberAllah.png"
    End Sub

 

No comments:

Post a Comment

Search This Blog (raadi)