无意中在一个源码中发现这个无限级分类,欣喜之余发现存在不少Bug,发了不少精力进行修复,并附有祥细注释,现在拿出来分享,由于是从项目中直接Copy出来,所以有兴趣的人还需仔细看一下。源码如下(要是网易博客也能象Csdn那样标明代码就好了):
表:Ye_Chennel结构
![.net(c)产品无限级分类 - zhenhua.ye - zhenhua.ye的博客 .net(c)产品无限级分类 - zhenhua.ye - zhenhua.ye的博客](http://img.ph.126.net/j5VEa_pc6lV0ZpBHqvlNmA==/3249065656172576761.jpg)
List.cs(会用到的一些函数,放在App_Code)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
/// <summary>
///List 的摘要说明
/// </summary>
public class List
{
public List()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 获得栏目类别列表,绑定到DropDownList
/// </summary>
/// <param name="DropDownList1"></param>
/// <param name="dt"></param>
public void GetChennel(DropDownList DropDownList1, DataTable dt)
{
if (dt.Rows.Count>0)
{
foreach (DataRow dr in dt.Rows)
{
if(Convert.ToInt32(dr["ch_father"].ToString())==0) //从顶级栏目开始
{
DropDownList1.Items.Add(dr["ch_name"].ToString());
BindDropChildItem(DropDownList1,dt,Convert.ToInt32(dr["id"].ToString()),1);
}
}
}
}
/// <summary>
/// 绑定子节点
/// </summary>
/// <param name="DropDownList1"></param>
/// <param name="dt"></param>
/// <param name="id">父ID</param>
/// <param name="length">子节点前面空白的长度</param>
public void BindDropChildItem(DropDownList DropDownList1, DataTable dt, long id, int length)
{
DataRow[] rows = dt.Select("ch_father='" + id + "'"); //取出id子节点进行绑定
for (int i = 0; i < rows.Length; i++)
{
string addName = SpaceLength(length) + "├" + rows[i]["ch_name"].ToString();
DropDownList1.Items.Add(addName);
BindDropChildItem(DropDownList1,dt,Convert.ToInt64(rows[i]["id"].ToString()),length+1);
}
}
/// <summary>
/// 添加产品,类别绑定
/// </summary>
/// <param name="DropDownList1"></param>
/// <param name="dt"></param>
public void GetProductChennel(DropDownList DropDownList1, DataTable dt)
{
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
if (Convert.ToInt32(dr["ch_father"]) == 0)
{
DropDownList1.Items.Add(new ListItem(dr["ch_name"].ToString(), dr["id"].ToString()));
BindChildItem(DropDownList1, dt, Convert.ToInt32(dr["id"]), 1);
}
}
}
}
/// <summary>
/// 递归添加产品,类别绑定
/// </summary>
/// <param name="DropDownList1"></param>
/// <param name="dt"></param>
/// <param name="id">父ID</param>
/// <param name="length">子节点前面空白的长度</param>
public void BindChildItem(DropDownList DropDownList1, DataTable dt, int id, int length)
{
DataRow[] cdr = dt.Select("ch_father=" + id + "");
for (int i = 0; i < cdr.Length; i++)
{
string name = SpaceLength(length) + "├" + cdr[i]["ch_name"].ToString();
DropDownList1.Items.Add(new ListItem(name, cdr[i]["id"].ToString()));
BindChildItem(DropDownList1, dt, Convert.ToInt32(cdr[i]["id"]), length + 1);
}
}
/// <summary>
/// 子节点前面空白的长度
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
public string SpaceLength(int i)
{
string space = "";
for (int j = 0; j < i; j++)
{
space += " "; 注意这里的空白是智能abc输入法状态下的v11字符;
}
return space;
}
}
DBFun.cs(对数据库相关操作,放在App_code)
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.Text.RegularExpressions;
using System.Data.OleDb;
using Wuqi.Webdiyer;
/// <summary>
///DBFun 的摘要说明
/// </summary>
public class DBFun
{
protected static OleDbConnection conn = new OleDbConnection();
protected static OleDbCommand comm = new OleDbCommand();
public DBFun()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 打开数据库
/// </summary>
private static void openConnection()
{
if (conn.State.Equals(ConnectionState.Closed))
{
conn.ConnectionString = "Provider=Microsoft.Jet.OlEDB.4.0;Data Source=" +
System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.ConnectionStrings["DBPath"].ToString());
comm.Connection = conn;
try
{
conn.Open();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
}
/// <summary>
/// 关闭数据库
/// </summary>
private static void closeConnection()
{
if (conn.State.Equals(ConnectionState.Open))
{
conn.Close();
conn.Dispose();
comm.Dispose();
}
}
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sqlstr">要执行的sql语句</param>
public static void ExecuteSql(string sqlstr)
{
try
{
openConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlstr;
comm.ExecuteNonQuery();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
}
/// <summary>
/// 执行更新
/// </summary>
/// <param name="sqlstr">传入要更新的SQL语句</param>
/// <returns></returns>
public static bool ExecuteUpdate(string sqlstr)
{
int isUpdateOk = 0;
try
{
openConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlstr;
isUpdateOk = Convert.ToInt32(comm.ExecuteNonQuery());
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
if (isUpdateOk > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 查询数据,取得首行
/// </summary>
/// <param name="sqlstr">要查询的sql语句</param>
/// <returns>返回第一行数据</returns>
public static DataRow GetDataRow(string sqlstr)
{
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
return ds.Tables[0].Rows[0];
else
return null;
}
catch
{
return null;
}
finally
{
closeConnection();
}
}
/// <summary>
/// /查询数据,取得数据视图
/// </summary>
/// <param name="sqlstr">要查询的sql语句</param>
/// <returns>取得数据视图</returns>
public static DataView GetDataDiew(string sqlstr)
{
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0].DefaultView;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
}
/// <summary>
/// 用SQL语句填充下拉列表
/// </summary>
/// <param name="ddlist">DropDownList</param>
/// <param name="sqlStr">填充的数据源</param>
public static void FillDwList(DropDownList ddlist, string sqlStr)
{
try
{
DataView dv = GetDataDiew(sqlStr);
ddlist.DataValueField = dv.Table.Columns[0].Caption.ToString();
ddlist.DataTextField = dv.Table.Columns[1].Caption.ToString();
ddlist.DataSource = dv;
ddlist.DataBind();
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行Sql查询语句并返回第一行的第一条记录,返回值为object 使用时需要拆箱操作 -> Unbox
/// </summary>
/// <param name="sqlStr">传入的Sql语句</param>
/// <returns>object 返回值 </returns>
public static object ExecuteScalar(string sqlStr)
{
object obj = new object();
try
{
openConnection();
comm.CommandType = CommandType.Text;
comm.CommandText = sqlStr;
obj = comm.ExecuteScalar();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
return obj;
}
/// <summary>
/// 返回指定Sql语句的SqlDataReader,请注意,在使用后请关闭本对象,同时将自动调用closeConnection()来关闭数据库连接
/// 方法关闭数据库连接
/// </summary>
/// <param name="sqlstr">传入的Sql语句</param>
/// <returns>SqlDataReader对象</returns>
public static OleDbDataReader DataReader(string sqlstr)
{
OleDbDataReader dr = null;
try
{
openConnection();
comm.CommandText = sqlstr;
comm.CommandType = CommandType.Text;
dr = comm.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
dr.Close();
}
finally
{
closeConnection();
}
return dr;
}
/// <summary>
/// 返回指定Sql语句的DataTable
/// </summary>
/// <param name="sqlstr">传入的Sql语句</param>
/// <returns>DataTable</returns>
public static DataTable GetDataTable(string sqlStr)
{
DataTable dt=new DataTable();
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sqlStr, conn);
da.Fill(dt);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
return dt;
}
/// <summary>
/// 返回dataset
/// </summary>
/// <param name="sqlStr"></param>
/// <returns></returns>
public static DataSet GetDataSet(string sqlStr)
{
DataSet ds = new DataSet();
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sqlStr, conn);
da.Fill(ds);
return ds;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
}
/// <summary>
/// 返回dataset
/// </summary>
/// <param name="sqlStr"></param>
/// <param name="table"></param>
/// <returns></returns>
public static DataSet GetDataSet(string sqlStr,string table)
{
DataSet ds = new DataSet();
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sqlStr, conn);
da.Fill(ds,table);
return ds;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
}
/// <summary>
/// 绑定分页aspnetpage控件
/// </summary>
/// <param name="Page">aspnetPage控件</param>
/// <param name="sql">要查询的sql语句</param>
/// <param name="table"></param>
/// <returns>返回DataSet</returns>
public static DataSet Pager(AspNetPager Page, string sql, string table)
{
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, Page.PageSize * (Page.CurrentPageIndex - 1), Page.PageSize, table);
return ds;
}
catch(Exception e)
{
throw new Exception(e.Message, e);
}
finally
{
closeConnection();
}
}
/// <summary>
/// 记录数
/// </summary>
/// <param name="sql"></param>
/// <returns>返回记录数</returns>
public static int RecordCount(string sql)
{
try
{
openConnection();
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0].Rows.Count;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
closeConnection();
}
}
}
ChennelAdd.aspx(添加类别)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChennelAdd.aspx.cs" Inherits="YE_admin_ChennelAdd" %>
<!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 rel="Stylesheet" href="css/css.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="60%" border="0" align="center" cellpadding="1" cellspacing="1">
<tr>
<td colspan="2" id="tabletitlelink" style="FONT-WEIGHT: bold; FONT-SIZE: 12px; BACKGROUND-IMAGE: url(images/admin_bg_1.gif); COLOR: white; BACKGROUND-COLOR: #4455aa; "
align="center" height="25">添加栏目</td>
</tr>
<tr>
<td width="16%" align="right" class="forumRow">上级栏目:</td>
<td width="84%" class="forumRow">
<asp:DropDownList ID="DropDownList1" runat="server" Height="16px" >
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="right" class="forumRow">栏目名称:</td>
<td class="forumRow">
<asp:TextBox ID="cname" runat="server" Width="267px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="cname" ErrorMessage="栏目名称必填"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right" class="forumRow">排序:</td>
<td class="forumRow">
<asp:TextBox ID="corder" runat="server" Text="0"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="corder" ErrorMessage="只能为整数"
ValidationExpression="/d+"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right" class="forumRow">关键字:</td>
<td class="forumRow">
<asp:TextBox ID="ckeywords" runat="server" Width="335px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="forumRow">描述:</td>
<td class="forumRow">
<asp:TextBox ID="cdescription" runat="server" Height="60px" TextMode="MultiLine"
Width="333px"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center" class="forumRow">
<asp:Button ID="Button1" runat="server" CssClass="btn" Text="添加"
οnclick="Button1_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
ChennelAdd.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
public partial class YE_admin_ChennelAdd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add("顶级栏目");
string sql = "select * from Ye_chennel ";
DataTable dt = DBFun.GetDataTable(sql);
List li = new List();
li.GetChennel(DropDownList1, dt);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
long order, deep, father, ffather;
string name, keywords, description, child, sql, topname, childs, fchild, fchilds;
order = 0;
if(corder.Text!="")
{
order = Convert.ToInt64(corder.Text); //排序
}
name = cname.Text.Trim(); //栏目名称
keywords = ckeywords.Text.Trim(); //关键字
description = cdescription.Text.Trim(); //描述
child = "0"; //子节点,默认为0
fchild = ""; //父节点包含的子节点列
fchilds = ""; //
topname = ""; //上一级栏目的名称
if (DropDownList1.SelectedItem.Text == "顶级栏目")
{
deep = 0; //深度设置为0
father = 0; //父节点设置为0
}
else
{
topname = DropDownList1.SelectedItem.Text.Replace("├", "").Trim();
sql = "select * from Ye_Chennel where ch_name='" + topname + "'"; //找出父子节点这一行
DataRow dr = DBFun.GetDataRow(sql);
deep = Convert.ToInt64(dr["ch_deep"].ToString()) + 1; //深度加一
father = Convert.ToInt64(dr["id"]); //父节点的ID为子节点的父ID(ch_father)
}
//检查栏目是否存在
sql = "select id from Ye_Chennel where ch_name='" + name + "'";
if (DBFun.GetDataTable(sql).Rows.Count>0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert2", "<script>alert('该栏目已经存在');</script>");
return;
}
sql = "Insert Into Ye_chennel(ch_name,ch_child,ch_childs,ch_keywords,ch_description,ch_father,ch_deep,ch_order)values('" + name + "','" + child + "','" + child + "','" + keywords + "','" + description + "','" + father + "','" + deep + "','" + order + "')";
DBFun.ExecuteSql(sql);
//childs添加
sql = "select * from Ye_Chennel where ch_name='" + name + "'";
DataRow cDr = DBFun.GetDataRow(sql);
childs = cDr["id"].ToString(); //新添加的栏目的childs为该条目的ID
ffather = Convert.ToInt64(cDr["ch_father"]); //父ID
sql = "update Ye_chennel set ch_childs='" + childs + "' where ch_name='" + name + "'";
DBFun.ExecuteSql(sql);
//父栏目修改
if (DropDownList1.SelectedItem.Text != "顶级栏目")
{
while (ffather != 0)
{
sql = "select * from Ye_chennel where id=" + ffather; //父记录
DataRow fDr = DBFun.GetDataRow(sql);
fchild = fDr["ch_child"].ToString();
fchilds = fDr["ch_childs"].ToString();
string tmpname = fDr["ch_name"].ToString(); //父名称
long tmpfather = ffather; //父ID
ffather = Convert.ToInt64(fDr["ch_father"]); //父ID的上一级ID
if (tmpname == topname)
{
if (fchild == "0") //父记录的ch_child为0(没有子节点)
{
fchild = childs;
}
else
{
fchild += "," + childs;
}
}
fchilds = fchilds + "," + childs;
sql = "update Ye_chennel set ch_child='" + fchild + "',ch_childs='" + fchilds + "'where id=" + tmpfather;
DBFun.ExecuteSql(sql);
}
}
Response.Redirect("chennelADD.aspx");
}
}
ChennelEdit.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChennelEdit.aspx.cs" Inherits="YE_admin_ChennelEdit" %>
<!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 rel="Stylesheet" href="css/css.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="60%" border="0" align="center" cellpadding="1" cellspacing="1">
<tr>
<td colspan="2" id="tabletitlelink" style="FONT-WEIGHT: bold; FONT-SIZE: 12px; BACKGROUND-IMAGE: url(images/admin_bg_1.gif); COLOR: white; BACKGROUND-COLOR: #4455aa; "
align="center" height="25">修改栏目</td>
</tr>
<tr>
<td width="16%" align="right" class="forumRow">上级栏目:</td>
<td width="84%" class="forumRow">
<asp:DropDownList ID="DropDownList1" runat="server" Height="16px" >
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="right" class="forumRow">栏目名称:</td>
<td class="forumRow">
<asp:TextBox ID="cname" runat="server" Width="267px"></asp:TextBox>
排序:<asp:TextBox ID="corder" runat="server" Text="0"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="corder" ErrorMessage="只能为整数"
ValidationExpression="/d+"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="right" class="forumRow">关键字:</td>
<td class="forumRow">
<asp:TextBox ID="ckeywords" runat="server" Width="335px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="forumRow">描述:</td>
<td class="forumRow">
<asp:TextBox ID="cdescription" runat="server" Height="60px" TextMode="MultiLine"
Width="333px"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center" class="forumRow">
<asp:Button ID="Button1" runat="server" CssClass="btn" Text="修改"
οnclick="Button1_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
ChennelEdit.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
public partial class YE_admin_ChennelEdit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CommFun.IsAdmin();
int id = Convert.ToInt32(Request.QueryString["id"]);
if (id != 0)
{
DropDownList1.Items.Clear();
DropDownList1.Items.Add("顶级栏目");
string sql = "select * from Ye_chennel ";
DataTable dt = DBFun.GetDataTable(sql);
List li = new List();
li.GetChennel(DropDownList1, dt);
//sql = "select * from Ye_chennel where id=" + id + " ";
DataRow[] rows = dt.Select("id=" + id + "");
DataRow row = rows[0]; //要修改的记录
cname.Text = row["ch_name"].ToString();
corder.Text = row["ch_order"].ToString();
ckeywords.Text = row["ch_keywords"].ToString();
cdescription.Text = row["ch_description"].ToString();
int father = Convert.ToInt32(row["ch_father"]);
if (father != 0)
{
rows = dt.Select("id=" + father + "");
row = rows[0];
string fathername = row["ch_name"].ToString();
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
if (DropDownList1.Items[i].Text.Replace("├", "").Replace(" ","")==fathername)
{
DropDownList1.SelectedValue = DropDownList1.Items[i].Text;
}
}
}
}
else
{
Response.Redirect("ChennelList.aspx");
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
int order, deep, father;
string name, keyword, description;
name = cname.Text;
keyword = ckeywords.Text;
description = cdescription.Text;
order = Convert.ToInt32(corder.Text);
string topName = DropDownList1.SelectedItem.Text.Replace("├", "").Trim(); //新的上一级栏目名
string sql="select * from Ye_chennel where id="+id+" ";
DataRow oldDr = DBFun.GetDataRow(sql); //要修改的记录
int oldDeep = Convert.ToInt32(oldDr["ch_deep"]); //原来的深度
DataRow fatherDr = DBFun.GetDataRow("select * from Ye_Chennel where ch_name='" + topName + "'"); //新的父节点所在行
string fatherId = "0";
if (topName == "顶级栏目")
{
fatherId = "0";
}
else
{
fatherId = fatherDr["id"].ToString();
}
if (oldDr["ch_childs"].ToString().IndexOf(fatherId)>=0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert2", "<script>alert('不能移动到以其自身或子类做为其新的父类');</script>");
return;
}
sql = "select * from Ye_chennel where ch_name='" + name + "' and id<>"+id+" ";
if (DBFun.GetDataTable(sql).Rows.Count > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert2", "<script>alert('该栏目已经存在');</script>");
return;
}
if (topName == "顶级栏目")
{
deep = 0;
father = 0;
}
else
{
deep = Convert.ToInt32(fatherDr["ch_deep"])+1; //新的深度为父深度加1
father = Convert.ToInt32(fatherDr["id"]); //新的父节点为所选节点的ID
}
sql = String.Format("update Ye_chennel set ch_name='{0}',ch_keywords='{1}',ch_description='{2}',ch_father={3},ch_deep={4},ch_order={5} where id={6}", name, keyword, description, father, deep, order, id);
DBFun.ExecuteSql(sql); //栏目修改
//下级栏目深度修改,当前深度与原来深度不等
if (oldDeep != deep)
{
ChildDeep(oldDr["ch_child"].ToString(), (deep + 1));
}
//删除以前上级栏目child,childs
int oldfather = Convert.ToInt32(oldDr["ch_father"]); //原来的上一级ID
//string oldchild = oldDr["ch_child"].ToString();
string oldchild = id.ToString();
string oldchilds = oldDr["ch_childs"].ToString(); //修改行的childs
if (father !=oldfather )
{
int tempfather = oldfather;
while (tempfather != 0)
{
sql = "select * from Ye_chennel where id=" + tempfather + ""; //原来上一级的记录
DataRow oldFatherOld = DBFun.GetDataRow(sql);
string tempchild = oldFatherOld["ch_child"].ToString();
string tempchilds = oldFatherOld["ch_childs"].ToString();
string tempname = oldFatherOld["ch_name"].ToString();
tempfather = Convert.ToInt32(oldFatherOld["ch_father"]); //再一级
tempchild = oldChildDel(tempchild, oldchild); //删除child
tempchilds = oldChildsDel(tempchilds, oldchilds);
sql = string.Format("update Ye_chennel set ch_child='{0}',ch_childs='{1}' where ch_name='{2}'", tempchild, tempchilds, tempname);
DBFun.ExecuteSql(sql);
}
}
//如果不是顶级栏目,向上级栏目添加子栏目
if (father != 0)
{
int tempfather = father;
int x = 0;
while (tempfather != 0)
{
sql = "select * from Ye_chennel where id=" + tempfather + ""; //新的父类的记录
DataRow newFatherRow = DBFun.GetDataRow(sql);
string tempchild = newFatherRow["ch_child"].ToString();
string tempchilds = newFatherRow["ch_childs"].ToString();
tempfather = Convert.ToInt32(newFatherRow["ch_father"]);
string tempname=newFatherRow["ch_name"].ToString();
if (x == 0)
{
if(tempchild.IndexOf(id.ToString())>0)
{
tempchild = tempchild + "," + id.ToString();
}
x = 1;
}
tempchilds = newFatherChild(tempchilds, oldchilds);
sql = "update Ye_chennel set ch_child='" + tempchild + "',ch_childs='" + tempchilds + "' where ch_name='" + tempname + "'";
DBFun.ExecuteSql(sql);
}
}
ClientScript.RegisterStartupScript(this.GetType(), "alert3", "<script>alert('修改成功');location.href='chennelList.aspx';</script>");
}
/// <summary>
/// 向新的父类中添加child,childs
/// </summary>
/// <param name="fatherChild"></param>
/// <param name="newChild"></param>
/// <returns></returns>
public string newFatherChild(string fatherChild, string newChild)
{
char[] douhao = { ',' };
string[] arrstr = newChild.Split(douhao);
foreach (string m in arrstr)
{
if (fatherChild.IndexOf(m) < 0)
{
fatherChild += "," + m;
}
}
return fatherChild;
}
/// <summary>
/// 删除原来父类的child
/// </summary>
/// <param name="oldFatherchild">原来父类的child</param>
/// <param name="childId">修改行的ID</param>
/// <returns></returns>
public string oldChildDel(string oldFatherchild,string childId)
{
if (oldFatherchild.IndexOf("," + childId) >= 0)
{
oldFatherchild = oldFatherchild.Replace("," + childId, "");
}
else
{
if (oldFatherchild.IndexOf(childId + ",") >= 0)
{
oldFatherchild = oldFatherchild.Replace(childId + ",", "");
}
else
{
oldFatherchild = oldFatherchild.Replace(childId,"");
if (oldFatherchild.Trim() == "")
{
oldFatherchild = "0";
}
}
}
return oldFatherchild;
}
/// <summary>
/// 删除原来父行的childs
/// </summary>
/// <param name="oldFatherchilds"></param>
/// <param name="childs"></param>
/// <returns></returns>
public string oldChildsDel(string oldFatherchilds, string childs)
{
char[] douhao = { ',' };
string[] arrstr = childs.Split(douhao);
foreach (string m in arrstr)
{
if (oldFatherchilds.IndexOf(m) >= 0)
{
oldFatherchilds = oldFatherchilds.Replace("," + m, "");
}
}
return oldFatherchilds;
}
/// <summary>
/// 修改子节深度
/// </summary>
/// <param name="oldChild">子节点ID</param>
/// <param name="newDeep">新的深度</param>
public void ChildDeep(string oldChild,int newDeep)
{
char[] douhao = { ',' };
if (oldChild != "0")
{
string[] arrstr = oldChild.Split(',');
foreach (string m in arrstr)
{
DBFun.ExecuteSql("update Ye_chennel set ch_deep=" + newDeep + " where id=" + Convert.ToInt32(m) + ""); //修改子节点的深度
string ooChild = (string)DBFun.ExecuteScalar("select ch_child from Ye_chennel where id=" + Convert.ToInt32(m) + ""); //获得要修改下一节点的ID
if (ooChild != "0")
{
ChildDeep(ooChild, newDeep + 1);
}
}
}
}
}