注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 Cisco IOS下载
 帮助

VS2005中动态生成树状菜单


2008-03-15 08:06:09
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://zhcsmx22.blog.51cto.com/287943/65842
一个像CSDN一样的树型菜单导航,用的是VS2005自带的TreeView控件。主要代码是生成树的递归函数。
 
后台代码:
 
using System;
using System.Data;
using System.Configuration;
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection Conn = new SqlConnection("server=OEM-MICRO;database=Test;uid=user;pwd=");
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
        Conn.Open();
        this.createDataSet();
        Conn.Close();
        this.InitTree(tvMenu.Nodes, "0");
    }
    private DataSet createDataSet()
    {
        ds = new DataSet();
        string sqlStr = "select * from Tree ";
        SqlDataAdapter cmdSelect = new SqlDataAdapter(sqlStr, Conn);
        cmdSelect.Fill(ds, "Tree");
        return ds;
    }
    protected void InitTree(TreeNodeCollection Nds, string parentId)//用递归方法动态生成节点
    {
        DataView dv = new DataView();
        TreeNode tmpNode;
        dv.Table = ds.Tables["Tree"];
        dv.RowFilter = "ParentId=" + "'" + parentId + "'";
        foreach (DataRowView drv in dv)
        {
            tmpNode = new TreeNode();
            tmpNode.Value = drv["Id"].ToString();
            tmpNode.Text = drv["Name"].ToString();
            tmpNode.NavigateUrl = "#";
            Nds.Add(tmpNode);
            this.InitTree(tmpNode.ChildNodes, tmpNode.Value);
        }
    }
}
 
 
 
页面代码:
 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
        <asp:TreeView ID="tvMenu" runat="server" ImageSet="Faq" ShowLines="True" ExpandDepth="0" Target="middle" >
            <ParentNodeStyle Font-Bold="False" />
            <HoverNodeStyle Font-Underline="True" ForeColor="Purple" />
            <SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" VerticalPadding="0px" />
            <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="DarkBlue" HorizontalPadding="5px"
                NodeSpacing="0px" VerticalPadding="0px" />
        </asp:TreeView>
  
    </div>
    </form>
</body>
</html>

本文出自 “赵宏臣主页” 博客,请务必保留此出处http://zhcsmx22.blog.51cto.com/287943/65842





    文章评论
 
2008-03-16 19:31:25
不错 学习

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: