How To Use Tree Menu Based On User Credentials ( Logged In User / Not Logged In User).
What is this article about?
This article will demonstrate how to use a Tree Menu Control. If you need to allow sub menu's, or a tree like structure, this is your best bet.
You can view this control on your ToolBox in Visual Studio 2005. It is branched under [Navigation]. You will see some other menu controls such as SiteMapPath, and Menu.
Lets Get Started
This first thing we need to go is to create a master page. If you are not going to be using master pages, then create a user control called MyMenu which will have the Tree Menu control within it. For this example we will use the master page, which will give you an idea of how the Tree Menu control works. The reason you would want it in a user control, or in a master page, is that the Menu dynamically generates based on the user. You don't want to go to all you pages, and copy and paste the menu and it's code. This way you just do it once, and do not need to look back (Except for testing).
Once you created the master page, create the structure you would like to have. This is how I designed my master page:

The top part is just a label which is my logo.
The left side contains a Tree Menu Control. Just drag the control there from your toolbox under [Navigation -> TreeView]. You do not need to add any items, but you can right click, and click on AutoFormat to choose a different style. Below I used the MSDN style.


Great! Now that we have the menu format is setup, we will go to code behind page, and add some logic for the TreeMenu.
The Code:
/* The following code will generate the menu based on if the user is logged into the system. We will mark a session variable to show the user is logged in from our Login.aspx page(Later on in this article). This way the menu will dynamically generate. */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//Check if user is Logged in or not.
//We know this by checking for the Session["LoggedIn"] variable
if (Session["LoggedIn"] == null)
{
//================USER NOT LOGGED IN=======================
//Looks like we need to generate menu information
//Lets clear all the nodes.
//Why?, you may ask
//We clear it because it may have the Logged In Menu Stuff
TreeView1.Nodes.Clear();
//if the user is not logged in, we should have 3 nodes
//Home, Search, Login
TreeNode ndHome = new TreeNode("Home", "Home", "", "~/Home.aspx", "");
TreeNode ndSearch = new TreeNode("Search", "Search", "", "~/Search.aspx", "");
TreeNode ndLogin = new TreeNode("Login", "Login", "", "~/Login.aspx", "");
//Add the 3 nodes to the TreeView
TreeView1.Nodes.Add(ndHome);
TreeView1.Nodes.Add(ndSearch);
TreeView1.Nodes.Add(ndLogin);
}
else
{
//================USER LOGGED IN=======================
//Looks like we need to generate menu information
//Lets clear all the nodes.
//Why?, you may ask
//We clear it because it may have the Not Logged In Menu Stuff
TreeView1.Nodes.Clear();
//if the user is not logged in, we should have 3 nodes
//Home, Search, Advanced Search, and Logout
TreeNode ndHome = new TreeNode("Home", "Home", "", "~/Home.aspx", "");
TreeNode ndSearch = new TreeNode("Search", "Search", "", "~/Search.aspx", "");
TreeNode ndAdvancedSearch = new TreeNode("Advanced Search",
"Advanced Search",
"",
"~/AdvancedSearch.aspx", "");
TreeNode ndLogout = new TreeNode("Logout", "Logout", "", "~/Logout.aspx", "");
//Add nodes to the TreeView Control
TreeView1.Nodes.Add(ndHome);
TreeView1.Nodes.Add(ndSearch);
TreeView1.Nodes[1].ChildNodes.Add(ndAdvancedSearch);
TreeView1.Nodes.Add(ndLogout);
}
}
}
}
//=============================================================
Now we will generate our pages. Create the following webpages:
************** Make sure you select the option "Select Master Page" when creating the pages. ************
************** This will allow you to choose the master page we have just created. ********************
Pages:Home.aspx
Login.aspx
Logout.aspx
Search.aspx
AdvancedSearch.aspx
Home.aspx
The home page can have some sample text. For this example, it will not have have any code behind, but be more descriptive.
Login.aspx
Here we will allow the user to login. Create 2 textbox's for the username and password, and a button to login. Put them inside a Table, with id Table1. Make sure it is a server control. You can do this by selecting the Table, Right clicking, and choosing: "Run as Server Control".
Once the user logs in, we will validate the user, and create a session variable to mark him/her as logged in. This will be used in our master page automatically to load the proper menu items. Here is a sample of the Login page I created:
I created a table which was a server control, with the username, password labels, and textboxs, and a button to log in within it.
If the user is validated, I hide this table by using Table1.Visible = false;
See source code below the image.

The source code for the login page:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//when the page loads, if need to check if the user is logged in or not.
if (IsPostBack == false)
{
if (Session["LoggedIn"] == null)
{
TABLE1.Visible = true;
}
else
{
TABLE1.Visible = false;
this.LblMessage.Text = "Welcome, User";
}
}
}
protected void BtnLogin_Click(object sender, EventArgs e)
{
if (TBUserName.Text.Trim().Length > 0 && TBPassword.Text.Trim().Length > 0)
{
//you can check your database here, but for this example, we will just
//check against username: user, and password: pass
if (TBUserName.Text == "user" && TBPassword.Text == "pass")
{
//successfull logged in.
//redirect back to this page.
Session["LoggedIn"] = "LoggedIn";
Response.Redirect("~/Login.aspx");
}
else
{
this.LblMessage.Text = "* Invalid login information *";
return;
}
}
else
{
this.LblMessage.Text = "* Missing login information *";
}
}
}
Logout.aspx
Here we will clear the session so the user cannot see the logged in options from the main tree view menu.
The content for this page in this example is descriptive. It only lets the user know that they successfully logged out:

The source code for the logout page:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Logout : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Clear user sessions
Session["LoggedIn"] = null;
Session.Abandon();
}
}
Search.aspx
Here you would do your search features. For this example, it is more descriptive.

AdvancedSearch.aspx
Here you would do your advanced search features. For this example, it is more descriptive, except that we will check if the user is logged in.
Note: If a user who is not logged in, directly goes to the advanced search page, they will be automatically redirected to the regular search page.

Source Code for AdvancedSearch.aspx
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class AdvancedSearch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//User not logged in, they can only see regular search.
if (Session["LoggedIn"] == null)
{
Response.Redirect("~/Search.aspx");
}
}
}
//=======================================================================================
Thats it, now are you all set.
Run the application, and see how the Tree Menu changes based on when a user logs in.
If you have have roles, or want to incorporate roles into this solution, this is what you would do:
1. When a user logs in, create a session variable for this role, such as:
Session["UserRole"] = "member";
or
Session["UserRole"] = "admin";
or any other role you have
Session["UserRole"] = "Your Role";
2. In the master page, code behind, check what user role is in the logged in section:
if ( Session["UserRole"] != null && Session["UserRole"].ToString() == "admin")
{
//here add all the items the user has access to
//make sure the pages also check for the user role so users can't directly go to the pages.
}
3. Why do I need Roles?
It helps to maintain the site, and give some architecture to the site.
Here is a snap shot of the how menu looks when a user is not logged in (Check Tree Menu on left side below):
Here is a snap shot of the how menu looks when a user is logged in (Check Tree Menu on left side below):

I hope this tutorial helped you. Leave some feedback if you liked it, or had any questions.
This example was done in Visual Studio 2005 using Framework 2.0. I hope it shows you how to use a dynamic tree menu control with master pages. Good luck.
Was this article helpful? Don't forget to rate it. Ratings helps community members identify top & useful articles.