A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 赵大宝 中级黑马   /  2012-10-29 18:28  /  1563 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

在asp.net 2.0中,要动态从数据库中取出内容,动态增加结点,其实不难,比如以SQL SERVER 2000的PUBS数据库为例子,要以树型列表方式,取出作者,做为根结点,然后取出每位作者写过什么书,作为子结点,可以这样

<%@ Page Language="C#"%>
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient"%>
<%@ Import Namespace="System.Configuration"%>

<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Population of the TreeView Control</title>
<script runat=server>
void Node_Populate(object sender,
System.Web.UI.WebControls.TreeNodeEventArgs e)
{
if(e.Node.ChildNodes.Count == 0)
{
switch( e.Node.Depth )
{
case 0:
FillAuthors(e.Node);
break;
case 1:
FillTitlesForAuthors(e.Node);
break;
}
}
}

void FillAuthors(TreeNode node)
{
string connString = System.Configuration.ConfigurationSettings.
ConnectionStrings["NorthwindConnnection"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("Select * From
authors",connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet authors = new DataSet();
adapter.Fill(authors);
if (authors.Tables.Count > 0)
{
foreach (DataRow row in authors.Tables[0].Rows)
{
TreeNode newNode = new
TreeNode(row["au_fname"].ToString() + " " +
row["au_lname"].ToString(),
row["au_id"].ToString());
newNode.PopulateOnDemand = true;
newNode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(newNode);
}
}
}

void FillTitlesForAuthors(TreeNode node)
{
string authorID = node.Value;
string connString = System.Configuration.ConfigurationSettings.
ConnectionStrings["NorthwindConnnection"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command = new SqlCommand("Select T.title,
T.title_id From titles T" +
" Inner Join titleauthor TA on
T.title_id = TA.title_id " +
" Where TA.au_id = '" + authorID + "'", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet titlesForAuthors = new DataSet();
adapter.Fill(titlesForAuthors);
if (titlesForAuthors.Tables.Count > 0)
{
foreach (DataRow row in titlesForAuthors.Tables[0].Rows)
{
TreeNode newNode = new TreeNode(
row["title"].ToString(), row["title_id"].ToString());
newNode.PopulateOnDemand = false;
newNode.SelectAction = TreeNodeSelectAction.None;
node.ChildNodes.Add(newNode);
}
}
}

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeViewRunat="Server" ExpandImageUrl="Images/closed.gif"
CollapseImageUrl="Images/open.gif"
OnTreeNodePopulate="Node_Populate" ID="tvwauthors">
<Nodes>
<asp:TreeNodeText="Authors" PopulateOnDemand=true
Value="0"/>
</Nodes>
</asp:TreeView>
</div>
</form>
</body>
</html>
其中,注意ontreenodepopulate事件,是在展开树的结点时发生的,这里定义了自定义的NODE_POPULATE,在node_populate中,检查当前结点的深度,如果是0,就是根结点,于是就调用FillAuthors过程,取出所有的作者,如果深度是1,则是叶子结点,调用FillTitlesForAuthors过程。其中,要注意它们中的动态建立树结点的过程,如:
TreeNode newNode = new TreeNode(row["au_fname"].ToString() + " " +
row["au_lname"].ToString(),

row["au_id"].ToString());

newNode.PopulateOnDemand = true;

newNode.SelectAction = TreeNodeSelectAction.Expand;

node.ChildNodes.Add(newNode);
其中, popluateondemand属性表明,该结点会动态扩展

3 个回复

倒序浏览
太值得学习ing!
回复 使用道具 举报
许庭洲 发表于 2012-10-29 18:55
太值得学习ing!

{:3_49:} 。。。。。
回复 使用道具 举报
感觉看起来有点晕!下面是我自己做了一个新闻发布系统的后台管理项目菜单,遇到动态treeview,我是这么做的:
说明:我采用简单的三层架构来写的,带model的那种
1.首先在数据库先建表,然后建视图

这是model层代码,由于时间有点久,一时没找到,相信亲根据model也可以建出表和视图:
using System;
using System.Collections.Generic;
using System.Text;

namespace Model
{
    public class viewUserRightInfo
    {
        private string rolename;

        private int roleid;

        private int _funid;

        public int funid
        {
            get { return _funid; }
            set { _funid = value; }
        }
        private string _funname;

        public string funname
        {
            get { return _funname; }
            set { _funname = value; }
        }
        private string _funurl;

        public string funurl
        {
            get { return _funurl; }
            set { _funurl = value; }
        }

        private int _displayid;

        public int displayid
        {
            get { return _displayid; }
            set { _displayid = value; }
        }
        private int _fatherid;

        public int fatherid
        {
            get { return _fatherid; }
            set { _fatherid = value; }
        }
        private int userid;

        public int UserId
        {
            get { return userid; }
            set { userid = value; }
        }
        private string username;

        public string UserName
        {
            get { return username; }
            set { username = value; }
        }

        public int RoleId
        {
            get { return roleid; }
            set { roleid = value; }
        }

        public string RoleName
        {
            get { return rolename; }
            set { rolename = value; }
        }
    }
}





2.DAL层代码

public class viewUserRightInfoService
    {
        public static List<viewUserRightInfo> GetAllParentNodeInfoByUserId(int funid , int userid)
        {

            string sql = string.Format("select * from viewUserRightInfo where fatherid={0} and UserId ={1}",funid, userid);
            return datatables(sql);
        }

        public static List<viewUserRightInfo> select_by_roleid(int roleid)
        {
            string sql = string.Format("select * from viewUserRightInfo where  RoleId ={0}", roleid);
            return datatables(sql);
        }

        public static List<viewUserRightInfo> select_by_userid(int userid)
        {
            string sql = string.Format("select * from viewUserRightInfo where  UserId ={0}", userid);
            return datatables(sql);
        }
        public static viewUserRightInfo select_by_username(string username)
        {
            string sql = string.Format("select * from viewUserRightInfo where  UserName ='{0}'", username);
            return datarow(sql);
        }

        public static List<viewUserRightInfo> datatables(string sql)
        {
            List<viewUserRightInfo> list = new List<viewUserRightInfo>();
            viewUserRightInfo view = null;
            DataTable dt = SqlHelper.GetDataSet(sql);
            if (dt != null)
            {

                foreach (DataRow dr in dt.Rows)
                {
                    view = new viewUserRightInfo();
                    view.RoleName = (string)dr["RoleName"];
                    view.RoleId = (int)dr["roleid"];
                    view.funid = (int)dr["funid"];
                    view.funname = (string)dr["funname"].ToString();
                    view.funurl = (string)dr["funurl"].ToString();
                    view.displayid = (int)dr["displayid"];
                    view.fatherid = (int)dr["fatherid"];
                    view.UserId = (int)dr["UserId"];
                    view.UserName = (string)dr["UserName"].ToString();
                    list.Add(view);
                }
                return list;

            }
            else
            {
                return null;
            }

        }

        public static viewUserRightInfo datarow(string sql)
        {

            viewUserRightInfo view = null;
            DataRow dr = SqlHelper.GetDataSet(sql).Rows[0];
            if (dr != null)
            {
                view = new viewUserRightInfo();
                view.RoleName = (string)dr["RoleName"];
                view.RoleId = (int)dr["roleid"];
                view.funid = (int)dr["funid"];
                view.funname = (string)dr["funname"].ToString();
                view.funurl = (string)dr["funurl"].ToString();
                view.displayid = (int)dr["displayid"];
                view.fatherid = (int)dr["fatherid"];
                view.UserId = (int)dr["UserId"];
                view.UserName = (string)dr["UserName"].ToString();
                return view;
            }
            else
            {
                return null;
            }
        }


    }






3.BLL层代码
public class viewUserRightInfoManager
    {
        public static List<viewUserRightInfo> GetAllParentNodeInfoByUserId(int funid, int userid)
        {
            return viewUserRightInfoService.GetAllParentNodeInfoByUserId(funid, userid);
        }

        public static List<viewUserRightInfo> select_by_roleid(int roleid)
        {
            return viewUserRightInfoService.select_by_roleid(roleid);
        }


        public static List<viewUserRightInfo> select_by_userid(int userid)
        {
            return viewUserRightInfoService.select_by_userid(userid);
        }
        public static viewUserRightInfo select_by_username(string username)
        {
            return viewUserRightInfoService.select_by_username(username);
        }
    }



4.后台代码

    private TreeNode CreatTreaNode(string strText, int strId, string strUrl, string strImage)
    {
        TreeNode newNode = new TreeNode();
        newNode.Text = strText.ToString();
        newNode.Value = strId.ToString();
        newNode.NavigateUrl = strUrl;
        newNode.ImageUrl = strImage;
        return newNode;
    }

    private void Display(User user)
    {
        int roleid = (int)user.RoleId;


                TreeView1.Nodes.Clear();
                List<viewUserRightInfo> parent =viewUserRightInfoManager.GetAllParentNodeInfoByUserId(0, (int)user.UserId);
                foreach (viewUserRightInfo sf in parent)
                {
                    int nodeid = sf.funid;
                    string funname = sf.funname;
                    string image = "../Image/plugin_add.png";
                    TreeNode fatherNode = this.CreatTreaNode(funname, nodeid, "", image);
                    CreateChildTree(nodeid, (int)user.UserId, fatherNode);
                    TreeView1.Nodes.Add(fatherNode);
                }

        }

    private void CreateChildTree(int nodeid, int userid, TreeNode fatherNode)
    {

        List<viewUserRightInfo> child = viewUserRightInfoManager.GetAllParentNodeInfoByUserId(nodeid, userid);
        foreach (viewUserRightInfo sfchild in child)
        {
            int id = sfchild.funid;
            string childname = sfchild.funname;
            string nodeurl = ResolveUrl(sfchild.funurl.Trim());
            string image = "../Image/plugin_edit.png";
            TreeNode childNode = this.CreatTreaNode(childname, nodeid, nodeurl, image);
            CreateChildTree(id, userid, fatherNode);
            AddTree(fatherNode, childNode);
        }

    }

    private void AddTree(TreeNode fathernode, TreeNode chilenode)
    {
        fathernode.ChildNodes.Add(chilenode);
    }


        //List<Roleright> list = new List<Roleright>();
        //list = RolerightManager.select_by_roleid(roleid);
        //for (int i = 0; i < list.Count; i++)
        //{
        //    int nodeid = list[i].Funid;
        //    List<Funinfo> funlist = Funinfomessage.select_by_funid(nodeid);
        //    for (int j = 0; j < funlist.Count; j++)
        //    {

        //        TreeNode fathernode = CreatNode(funlist[j].Funname.ToString(), "");
        //        int fatherid = funlist[j].Funid;
        //        List<Funinfo> fulist = Funinfomessage.select_by_fatherid(fatherid);

        //        for (int e = 0; e < fulist.Count; e++)
        //        {

        //                TreeNode chilenode = CreatNode(fulist[e].Funname.ToString(), fulist[e].Funurl.ToString());

        //                fathernode.ChildNodes.Add(chilenode);

        //        }
        //        this.TreeView1.Nodes.Add(fathernode);

        //    }

        //}

    //}


    private TreeNode CreatNode(string strtext, string strurl)
    {
        TreeNode node = new TreeNode();
        node.Text = strtext;
        node.NavigateUrl = strurl;
        return node;
    }
}        以上有什么问题和建议请回复,我一直都用这个很好用的,还可以对这些节点进行管理,增删改









回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马