In the developing environment of C# and .NET, dynamic data binding isn’t anything new at all. I’m here just to make a summary of how to do the job to a TreeView object, and add a few contents depending on my practical experience.
Keywords: dynamic tree construction, user role, page.
Problem Description
In the classic three-layer architecture adopted by my project, we have
1. data tables that are dealt with by a DAL-located class database.cs;
2. a series of corresponding BLL classes to manipulate data retrieved from those tables;
3. aspx pages and aspx.cs code files in the presentation layer.
which means following elements are involved:
1. data table User, UserRole, RoleTree;
2. class User.cs, UserRole.cs, RoleTree.cs;
3. example page sampleTree.aspx and its code file sampleTree.aspx.cs.
A picture speaks more than a thousand words. Let’s first take a look at the chart below to get an overview of how this work is going to be done.
Solution Pt1: User Login
By the input username and password, we first get the userId, through which user role(s) are obtained and stored in a Session object. In case of more than one role for a specific user, we take an ArrayList as the role container.
if (Page.IsValid)
{
User usr = new User();
string userId = "";
SqlDataReader recs = usr.GetUserLogin(txtUserName.Text.Trim(), txtPassword.Text.Trim());
if (recs.Read())
{
userId = recs["UserID"].ToString();
}
recs.Close();
if ((userId != String.Empty) && (userId != ""))
{
// get user roles, put them into session
ArrayList alRoleIDs = new ArrayList();
UserRole ur = new UserRole();
SqlDataReader dr = ur.GetRoleByUserID(Int32.Parse(userId));
while (dr.Read())
{
alRoleIDs.Add(Int32.Parse(dr["RoleID"].ToString()));
}
Session.Add("RoleIDs", alRoleIDs);
dr.Close();
}
Solution Pt2: Tree Construction
Then we take the RoleIDs of ArralyList above and some PageID of int as arguments to get the tree. Codes below are sample codes from sampleTree.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindTreeData(treeSidebar, (ArrayList)Session["RoleIDs"]);
}
}
private void BindTreeData(TreeView tv, ArrayList al)
{
RoleTree rt = new RoleTree();
// when applied to different pages, take RoleIDs of ArrayList and PageID of int as arguments
DataTable dt = rt.GetTreeByRoleIDandPageID(al, 3); // 3 is an exmaple of pageId
tv.Nodes.Clear();
foreach (DataRow row in dt.Select())
{
TreeNode tempNode = new TreeNode();
tempNode.Text = row["Title"].ToString();
tempNode.Value = row["NodeID"].ToString();
tempNode.Expanded = false;
tempNode.NavigateUrl = row["Url"].ToString();
tv.Nodes.Add(tempNode);
}
}
Further Notice
//It is especially useful when applied to MasterPages.
//This solution does not take node’s parent into account, which means the TreeView object constructed is not a real tree, strictly speaking.