树的操作(绑定数据库,添加新节点,删除节点)(转载加实现)

前台:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="Master_MasterPage" %>

<!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>
    
<link href="../App_Themes/myTheme/Basic.css" rel="stylesheet" type="text/css" />
</head>
<body style="margin:0">
    
<form id="form1" runat="server">
    
<div>
    
<table style="width:100%;height:100%;border-collapse:collapse;border-color:#44a938" border="1""">
    
<tr><td style="height:50px; font-size:15px" colspan="2" align="center">God is a girl!</td></tr>
        
            
<tr>
                
<td style="width: 160px" valign="top">
                 
<asp:TreeView ID="TreeLeft" runat="server" ShowLines="True" OnSelectedNodeChanged="TreeLeft_SelectedNodeChanged" >
                    
</asp:TreeView>
                    Parent:
<asp:DropDownList ID="ddlParentID" runat="server" Width="90px"></asp:DropDownList><br />
                    Text:
&nbsp; <asp:TextBox ID="txtNodeName" runat="server" Width="85px"></asp:TextBox><br />
                    
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                    
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
                
</td>
                
<td valign="top" >
                    
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                    
</asp:ContentPlaceHolder>
                
</td>
            
</tr>

       
</table>
    
</div>
    
</form>
</body>
</html>
后台:
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;
using System.Data.SqlClient;

public partial class Master_MasterPage : System.Web.UI.MasterPage
{
   
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (!IsPostBack)
        {
            TreeleftBind();
            bindGroup();
        }
    }
    
#region 绑定树
    
private void TreeleftBind()
    {
        
this.TreeLeft.Nodes.Clear();
        DataTable dt 
= master.Getdt();
        DataView dv 
= new DataView(dt);
        dv.RowFilter 
= "TreeParentID = 0";
        TreeNode node 
= new TreeNode();
        
foreach (DataRowView drv in dv)
        {
            node.Text 
= drv["TreeName"].ToString();
            node.Value 
= drv["ID"].ToString();
            node.Expanded 
= true;
            
this.TreeLeft.Nodes.Add(node);
            AddReplies(dt, node);
        }
    }
    
private void AddReplies(DataTable dt, TreeNode node)
    {

        DataView dv 
= new DataView(dt);
        
        dv.RowFilter 
= "TreeParentID='" + node.Value + "'";
        
foreach (DataRowView row in dv)
        {
            TreeNode replyNode 
= new TreeNode();
            replyNode.Text 
= row["TreeName"].ToString();
            replyNode.Value 
= row["ID"].ToString();
            replyNode.NavigateUrl 
= row["Link"].ToString();
            replyNode.Expanded 
= false;
            node.ChildNodes.Add(replyNode);
            replyNode.ShowCheckBox 
= true;
            
            AddReplies(dt, replyNode);
        }

    }
    
#endregion

    
#region 绑定DropDownList
    
private void bindGroup()
    {
        
this.ddlParentID.Items.Clear();
        DataTable dt 
= master.Getdt(); //获取所有节点
        if (dt.Rows.Count > 0)
        {
            
foreach (DataRow row in dt.Rows)
            {
                
if (row["TreeParentID"].ToString().Trim() == "0")//绑定根节点
                {
                    
this.ddlParentID.Items.Add(new ListItem(row["TreeName"].ToString(), row["Id"].ToString()));
                    
this.bindDropChildItem(this.ddlParentID, dt, row["ID"].ToString(), 1);
                }
            }
        }
    }
    
private void bindDropChildItem(DropDownList d, DataTable dt, string id, int length)
    {
        DataRow[] rows 
= dt.Select("TreeParentID='" + id + "'""Id ASC");//取出id子节点进行绑定
        for (int i = 0; i < rows.Length; i++)
        {
            
this.ddlParentID.Items.Add(new ListItem(this.SpaceLength(length) + rows[i]["TreeName"].ToString(), rows[i]["Id"].ToString()));
            
this.bindDropChildItem(d, dt, rows[i]["Id"].ToString(), length + 1);//空白数目加1
        }
    }
    
private string SpaceLength(int i)
    {
        
string space = "";
        
for (int j = 0; j < i; j++)
        {
            space 
+= "--";
        }
        
return space;
    }
    
#endregion

    
#region 动态增加节点
    
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        
string rootID = ddlParentID.SelectedValue.ToString();
        
string txtName = this.txtNodeName.Text;
        master.InsertNode(
"AutoTree""TreeName""TreeParentID",txtName,rootID);
        
this.txtNodeName.Text = "";
        TreeleftBind();
        bindGroup();
    }
    
#endregion

    
#region 动态删除节点
    
protected void btnDelete_Click(object sender, EventArgs e)
    {
        
if (TreeChecked() != 0)
        {
            
string strjavascript = "<script language='javascript'>alert('You cant delete the node which have childnode!')</script>";
            Page.ClientScript.RegisterStartupScript(
this.GetType(), "onclick", strjavascript);
        }
        
else
        {
            
foreach (TreeNode node in TreeLeft.CheckedNodes)
            {

                
string SelectTreeID = node.Value;
                master.DeleteRecords(SelectTreeID);
            }
            TreeleftBind();
            bindGroup();
        }
    }
    
protected int TreeChecked()
    {
        
int count = 0;
        
foreach (TreeNode node in this.TreeLeft.CheckedNodes)
        {
            
if (node.ChildNodes.Count > 0)
            {
                count 
= count + 1;
            }
        }
        
return count;
    }
    
#endregion

    
#region 页面跳转
    
protected void TreeLeft_SelectedNodeChanged(object sender, EventArgs e)
    {
        TreeNode node 
= TreeLeft.SelectedNode;
        
if (node.ChildNodes.Count != 0)
        {
            node.SelectAction 
= TreeNodeSelectAction.Expand;
            node.Expanded 
= true;
        }
        
else
        {
            
string url = "@" + node.NavigateUrl;
            Response.Redirect(url);
//数据库中LINK字段的数据为:~/WOW/Moniqi.aspx
            
//Response.Redirect(@"~/Yule/wowmoni.aspx");
            
        }
    }
    
#endregion
}

类:
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;

/// <summary>
/// Summary description for master
/// </summary>
public class master
{
    
    
public master()
    {
        
//
        
// TODO: Add constructor logic here
        
//
    }

    
/// <summary>
    
/// 删除节点
    
/// </summary>
    
/// <param name="datakey"></param>
    public static void DeleteRecords(string datakey)
    {
        
string strDelete = String.Format("DELETE FROM [AutoTree] where ID = {0}", datakey);
        GetDB.cmdExecute(strDelete);
    }

    
/// <summary>
    
/// 返回DataTable
    
/// </summary>
    
/// <returns></returns>
    public static DataTable Getdt()
    {
        SqlConnection cn 
= GetDB.GetConnect();
        
string strSQL = "select * from AutoTree";
        SqlDataAdapter da 
= new SqlDataAdapter(strSQL, cn);
        DataTable dt 
= new DataTable();
        da.Fill(dt);
        
return dt;
    }

    
/// <summary>
    
/// 为Tree添加新节点
    
/// </summary>
    
/// <param name="tblName"></param>
    
/// <param name="_TreeName"></param>
    
/// <param name="_TreeParentID"></param>
    
/// <param name="txtName"></param>
    
/// <param name="rootID"></param>
    public static void InsertNode(string tblName, string _TreeName, string _TreeParentID, string txtName,string rootID)
    {
        
using (SqlConnection Conn = GetDB.GetConnect())
        {
            SqlCommand cmd 
= new SqlCommand(String.Format("insert into {0} ({1},{2}) values (@TreeName,@TreeParentID)",tblName,_TreeName,_TreeParentID), Conn);
            cmd.Parameters.Add(
"@TreeName", SqlDbType.NVarChar, 50).Value = txtName;
            cmd.Parameters.Add(
"@TreeParentID", SqlDbType.NVarChar, 50).Value = rootID;
            Conn.Open();
            cmd.ExecuteNonQuery();
            Conn.Close();
        }
    }
}
图:
   
posted @ 2007-11-29 14:00  早班火车  阅读(706)  评论(1编辑  收藏  举报