1. Tạo 1 dự án tên là: TreeView.
2. Tạo 1 file tên là: tree.aspx
3. Trong file tree.aspx copy dòng code sau vào:
<table width=”100%” cellpadding=”0″ cellspacing=”0″ align=”left”>
<tr>
<td><b>
Lựa chọn danh mục để quản lý nội dung</b>
</td>
</tr>
<tr>
<td align=”left” valign=”top” colspan=”2″ style=”padding-top:5px;”>
<asp:TreeView
ID=”TreeView1″
ExpandDepth=”fullyExpand”
PopulateNodesFromClient=”true”
ShowLines=”true”
ShowExpandCollapse=”true”
runat=”server” OnTreeNodePopulate=”TreeView1_TreeNodePopulate1″ />
</td>
</tr>
</table>
4. Bây giờ ta viết code cho menu này bind dữ liệu từ database(db). Trong file tree.cs copy dòng code sau vào:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
clsDBengine db = new clsDBengine();//mo ket noi den database
db.OPenDB();
PopulateRootLevel();
db.CloseDB();
//dong ket noi db
}
}
private void PopulateRootLevel()
{
string where_ = ” “;
//
string sql = “select catnews_id,catnews_name,catparent_id “;
sql += ” ,(select count(1) FROM tbl_catnewscms WHERE catparent_id=cms.catnews_id and isdelete=0 ” + where_ + “) as childnodecount “;
sql += ” FROM tbl_catnewscms as cms where catparent_id=0 and isdelete=0 ” + where_ + ” order by catnews_order “;
DataTable dt = db.ResutSQLText(sql);
PopulateNodes(dt, TreeView1.Nodes);
}
private void PopulateSubLevel(int parentid, TreeNode parentNode)
{
string where_ = ” “;
///
db = new clsDBengine();//mo ket noi den db
db.OPenDB();
string sql = “select catnews_id,catnews_name,catparent_id “;
sql += ” ,(select count(1) FROM tbl_catnewscms WHERE catparent_id=cms.catnews_id and isdelete=0 ” + where_ + ” ) as childnodecount “;
sql += ” FROM tbl_catnewscms as cms where catparent_id=” + parentid + where_ + ” and isdelete=0 order by catnews_order “;
DataTable dt = db.ResutSQLText(sql);
PopulateNodes(dt, parentNode.ChildNodes);
db.CloseDB();//dong ket noi den db
}
private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode();
string nodeid = dr[“catnews_id”].ToString();
string addnew = “<a href=\”addnewsx.aspx?parentID=” + nodeid + “\”>Thêm mới</a>”;
string text = “<b>” + dr[“catnews_name”].ToString() + “</b>”;
int subnode = 0;
try
{
subnode = int.Parse(dr[“childnodecount”].ToString().Trim());
}
catch { }
if (subnode == 0)
{
text = “<a href=’listnewsx.aspx?parentID=” + nodeid + “‘>” + dr[“catnews_name”].ToString() + “</a> | ” + addnew;
}
tn.Text = text;
tn.Value = dr[“catnews_id”].ToString();
nodes.Add(tn);
//If node has child nodes, then enable on-demand populating
tn.PopulateOnDemand = ((int)dr[“childnodecount”] > 0);
}
}
protected void TreeView1_TreeNodePopulate1(object sender, TreeNodeEventArgs e)
{
PopulateSubLevel(int.Parse(e.Node.Value), e.Node);
}