C#递归实现Treeview

无意发现在网上很刚学C#的朋友们都在找关于C#如何递归实现TreeView的绑定,见网上很多例子都比较深奥,我特意写了个比较简单易懂的例子帮助大家了解C#TreeView的操作与递归的实现...

本文只是用递归的方式简单实现TreeView的操作,可能存在性能上的问题,仅供初学者参考。

效果图:

一:创建数据库和数据表(Area)

二:创建AreaManage项目:

项目结构:

 

 

 

以下是各个类文件的代码:

1.SQLOperate.cs

///

///SQLOperate 的摘要说明 /// public class SQLOperate { /// /// 根据parentId查地区信息 /// /// /// public static DataTable GetAreaInfoByParentId(int parentId) { string sql = "select * from Area where ParentId = @ParentId"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@ParentId",parentId) }; return DBHelper.GetDataSet(sql, para); } /// /// 根据ID查找地区 /// /// /// public static DataTable GetAreaInfoById(int areaId) { string sql = "select * from Area where AreaId = @AreaId"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@Areaid",areaId)}; return DBHelper.GetDataSet(sql, para); } /// /// 增加同一级地区 /// /// /// /// public static int AddParityClass( int parentId,string areaName) { string sql = "insert into Area(AreaName,ParentId)values(@AreaName,@ParentId)"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@AreaName",areaName), new SqlParameter("@ParentId",parentId) }; return DBHelper.ExecuteCommand(sql, para); } /// /// 增加下一级地区 /// /// /// /// public static int AddNextClass(int parentId, string areaName) { string sql = "insert into Area(AreaName,ParentId)values(@AreaName,@ParentId)"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@AreaName",areaName), new SqlParameter("@ParentId",parentId) }; return DBHelper.ExecuteCommand(sql, para); } /// /// 查询是否有子集 /// /// /// public static bool CheckNextClass(int parentId) { string sql = "select AreaId from Area where ParentId = @ParentId"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@ParentId",parentId)}; using(SqlDataReader reader = DBHelper.ExecuteReader(sql,para)) { if (reader.Read()) return true; else return false; } } /// /// 删除地区 /// /// /// public static int DeleteClass(int areaId) { string sql = "Delete from Area where AreaId = @AreaId"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("AreaId",areaId)}; return DBHelper.ExecuteCommand(sql, para); } /// /// 修改地区名 /// /// /// /// public static int ModifyClass(int areaId ,string areaName) { string sql = "Update Area set AreaName = @AreaName where AreaId = @AreaId"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@AreaName", areaName), new SqlParameter("@AreaId",areaId) }; return DBHelper.ExecuteCommand(sql, para); } }

2.DBHelper

 

///

///DBHelper 的摘要说明 /// public static class DBHelper { private static SqlConnection connection; public static SqlConnection Connection { get { //读配置文件 // string connectionString = ConfigurationManager.ConnectionStrings["数据库名"].ConnectionString.ToString(); string connectionString = "server=服务器;database=数据库名;uid=sa;pwd=sa"; if (connection == null) { connection = new SqlConnection(connectionString); connection.Open(); } else if (connection.State == System.Data.ConnectionState.Closed) { connection.Open(); } else if (connection.State == System.Data.ConnectionState.Broken) { connection.Close(); connection.Open(); } return connection; } } public static int ExecuteCommand(string safeSql) { SqlCommand cmd = new SqlCommand(safeSql, Connection); int result = cmd.ExecuteNonQuery(); return result; } public static int ExecuteCommand(string sql, SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); return cmd.ExecuteNonQuery(); } public static int ExecuteCommand(string sql, SqlParameter value) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.Add(value); int result = cmd.ExecuteNonQuery(); return result; } public static int ExecuteScalar(string safeSql) { SqlCommand cmd = new SqlCommand(safeSql, Connection); int result = (int)cmd.ExecuteScalar(); return result; } public static int ExecuteScalar(string sql, SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); int result = (int)cmd.ExecuteScalar(); return result; } public static int ExecuteScalar(string sql, SqlParameter value) { int result = 0; SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.Add(value); try { result = (int)cmd.ExecuteScalar(); } catch (Exception ex) { result = 0; } return result; } public static SqlDataReader ExecuteReader(string safeSql) { SqlCommand cmd = new SqlCommand(safeSql, Connection); SqlDataReader reader = cmd.ExecuteReader(); return reader; } public static SqlDataReader ExecuteReader(string sql, SqlParameter value) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.Add(value); SqlDataReader reader = cmd.ExecuteReader(); return reader; } public static SqlDataReader ExecuteReader(string sql, SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); SqlDataReader reader = cmd.ExecuteReader(); return reader; } public static DataTable GetDataSet(string safeSql) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(safeSql, Connection); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); return ds.Tables[0]; } public static DataTable GetDataSet(string sql, params SqlParameter[] values) { DataSet ds = new DataSet(); SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds); return ds.Tables[0]; } public static SqlDataReader GetReader(string safeSql) { SqlCommand cmd = new SqlCommand(safeSql, Connection); SqlDataReader reader = cmd.ExecuteReader(); return reader; } public static SqlDataReader GetReader(string sql, params SqlParameter[] values) { SqlCommand cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddRange(values); SqlDataReader reader = cmd.ExecuteReader(); return reader; } }

 

3.模板页(MasterPage.master):

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %> 地区管理

 

4.模板页后台代码:(MasterPage.master.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; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindTreeView(); } } ///

/// 初始化treeview /// private void BindTreeView() { TreeNode treeNode = new TreeNode("地区管理"); treeNode.Value = "-1"; treeNode.NavigateUrl = "Default.aspx"; PopulateTreeView(0, treeNode); tvArea.Nodes.Add(treeNode); } /// /// 递归绑定treeview 效率有待改进 /// /// /// private void PopulateTreeView(int parentId,TreeNode parentNodes) { DataView dv = SQLOperate.GetAreaInfoByParentId(parentId).DefaultView; try { foreach (DataRowView drv in dv) { TreeNode myTreeNode = new TreeNode(drv["AreaName"].ToString()); myTreeNode.Value = drv["AreaId"].ToString(); myTreeNode.NavigateUrl = "Default.aspx?id=" + drv["AreaId"].ToString(); parentNodes.ChildNodes.Add(myTreeNode); PopulateTreeView(Convert.ToInt32(drv["AreaId"]), myTreeNode); } } catch (StackOverflowException ex) //如果递归进入死循环会发生此异常 { Console.WriteLine(ex.Message.ToString()); } } }

 

5. Default.aspx 页面代码(只为显示效果,不曾考虑排版):

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

ID:
AreaName:
ParentId:
请输入地区名...
地区名:

 

6.Default.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; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Bind(); } } ///

/// 初始化数据 /// private void Bind() { int id = Convert.ToInt32(Request.QueryString["id"]); if (id == 0) { ; } else { DataTable dataTable = SQLOperate.GetAreaInfoById(id); lblAreaId.Text = dataTable.Rows[0]["AreaId"].ToString(); lblAreaName.Text = dataTable.Rows[0]["AreaName"].ToString(); lblParentId.Text = dataTable.Rows[0]["ParentId"].ToString(); } } /// /// 删除地区 /// /// /// protected void btnDel_Click(object sender, EventArgs e) { int id = Convert.ToInt32(Request.QueryString["id"]); if (id == 0) { Response.Write(""); } else { if (SQLOperate.CheckNextClass(id)) Response.Write(""); else { int result = SQLOperate.DeleteClass(id); if (result > 0) { Response.Write(""); } } } } /// /// 修改地区名 /// /// /// protected void btnModify_Click(object sender, EventArgs e) { int id = Convert.ToInt32(Request.QueryString["id"]); if (id == 0) { Response.Write(""); } else { DataTable dataTable = SQLOperate.GetAreaInfoById(id); int result = SQLOperate.ModifyClass(Convert.ToInt32(dataTable.Rows[0]["AreaId"].ToString()), txtAreaName.Text.ToString().Trim()); if (result > 0) Response.Write(""); } } /// /// 添加同级地区 /// /// /// protected void btnAddParityClass_Click(object sender, EventArgs e) { int id = Convert.ToInt32(Request.QueryString["id"]); if (id == 0) { Response.Write(""); } else { DataTable dataTable = SQLOperate.GetAreaInfoById(id); int result = SQLOperate.AddParityClass(Convert.ToInt32(dataTable.Rows[0]["ParentId"].ToString()), txtAreaName.Text.ToString().Trim()); if (result > 0) Response.Write(""); } } /// /// 添加子级地区 /// /// /// protected void btnAddNextClass_Click(object sender, EventArgs e) { int id = Convert.ToInt32(Request.QueryString["id"]); if (id == 0) { Response.Write(""); } else { DataTable dataTable = SQLOperate.GetAreaInfoById(id); int result = SQLOperate.AddNextClass(Convert.ToInt32(dataTable.Rows[0]["AreaId"].ToString()), txtAreaName.Text.ToString().Trim()); if (result > 0) Response.Write(""); } } }

 

此程序只为入门者参考,如果更好的实现,欢迎留言补充,共同学习...

你可能感兴趣的:(.NET)