比如说我有一个这样的树状图
很多人会在设计数据库的时候不由自主的加上parentid这个字段,那是因为没用利用好编号的原因,
如果我们对每个记录进行编号的时候是按照一定规律的话,就像上面的: FB FBM FBM1 FBM2 .......
按照规律来编号码,不仅可以放弃parentid这个辅助字段,而且用肉眼就知道父子关系!!!!
我的代码是这样的:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace treeTest1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//页面加载
private void Form1_Load(object sender, EventArgs e)
{
string sql = "select code , name from tbTree";
List<TreeNode> allNodes = GetAllNodes(sql, "code", "name");
/* 不用autoTreeview 手动写会灵活
CreateTree(allNodes);
List<TreeNode> roots = GetRootNodeList(allNodes);
BindTreeViewByCode(this.treeView2, roots);
* */
AutoTreeView(this.treeView2, allNodes);
}
MsDatabase dbHelper = new MsDatabase();
public List<TreeNode> GetAllNodes(string sqlRead, string codeField, string textField)
{
List<TreeNode> allNodes = new List<TreeNode>();
DataTable source = dbHelper.GetDataTable(sqlRead);
foreach (DataRow rowTmp in source.Rows)
{
TreeNode nodeTemp = new TreeNode();
nodeTemp.Name = rowTmp[codeField].ToString();
nodeTemp.Text = rowTmp[textField].ToString();
allNodes.Add(nodeTemp);
}
return allNodes;
}
//构成树
//找到父亲节点
private TreeNode GetFatherNode(string currentName, List<TreeNode> allNodes)
{
int count = currentName.Length;
while (count >= 1)
{
string fatherName = currentName.Substring(0, count - 1);
for (int i = 0; i < allNodes.Count; i++)
{
if (allNodes[i].Name == fatherName)
{
return allNodes[i];//out for
}
}
//计算器减一
count -= 1;
}//end while
return null;
}
//把孩子节点和父亲节点连起来
private void ConnectFatherAndChild(TreeNode child , TreeNode father)
{
father.Nodes.Add(child);
}
//生成树结构
public void CreateTree(List<TreeNode> allNodes)
{
foreach (TreeNode nodeTmp in allNodes)
{
//如果有爸爸
if (GetFatherNode(nodeTmp.Name , allNodes) != null)
{
TreeNode fatherTmp = GetFatherNode(nodeTmp.Name, allNodes);
ConnectFatherAndChild(nodeTmp, fatherTmp);
}
}//end foreach
}
//得到根节点,可能有多个根节点
public List<TreeNode> GetRootNodeList(List<TreeNode> allNode)
{
List<TreeNode> rootList = new List<TreeNode>();
for (int i = 0; i < allNode.Count; i++)
{
//没有爸爸就是根节点
if (allNode[i].Parent == null)
{
rootList.Add(allNode[i]);
}
}//end for
return rootList;
}
//把根节点绑定到treeview控件
public void BindTreeViewWithRoots(TreeView view, List<TreeNode> roots)
{
foreach (TreeNode nodeTmp in roots)
{
view.Nodes.Add(nodeTmp);
}
}
//全自动绑定treeview控件
public void AutoTreeView(TreeView view, List<TreeNode> allNodes)
{
CreateTree(allNodes);
List<TreeNode> roots = GetRootNodeList(allNodes);
BindTreeViewWithRoots(view, roots);
}
/
}//end class
}