C# 中 TreeView绑定数据库数据,目前这个这个只是一个demo,在项目中运用有些欠缺,以后会进行完善...
DataSet ds = sysDicTypeBll.GetAllList();
//把其他节点加上去
if (ds != null)
{
//往TreeView中添加树节点
//添加根节点
TreeNode tn = new TreeNode();
tn.Text = "所有数据字典类型";
tn.Name = "0";
tv.Nodes.Add(tn);
tv.SelectedNode = tv.TopNode;
//把其他节点加上去
if (ds != null)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
tn = new TreeNode();
tn.Text = dr["DicTypeName"].ToString();
tn.Name = dr["DicTypeId"].ToString();
tv.SelectedNode.Nodes.Add(tn);
}
tv.ExpandAll();//展开TreeView
tv.SelectedNode = tv.TopNode; //最顶端节点选中
}
}
C# 中 TreeView 常用的一些方法,属于个人收集及总结
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ShangwuFrame.CommonUI
{
public class TreeUtil
{
/// <summary>
/// 从数据库查询添加新的树节点到指定的父接点上
/// </summary>
/// <param name="parenTn">父接点</param>
/// <param name="newTn">新节点</param>
/// <param name="nodeText">新节点显示文本</param>
/// <param name="nodeName">新接点唯一值,数据表中的ID</param>
public static void AddTreeNode(TreeNode parenTn, TreeNode newTn, string nodeText, string nodeName)
{
newTn = new TreeNode(nodeText);
newTn.Name = nodeName;
parenTn.Nodes.Add(newTn);
}
/// <summary>
/// 添加数据到数据库的同时把数据添加到指定的树节点
/// </summary>
/// <param name="treeview">treeview组件</param>
/// <param name="parenTn">父节点</param>
/// <param name="newTn">新节点</param>
/// <param name="nodeText">新节点显示文本</param>
/// <param name="id">新接点唯一值,数据表中的ID</param>
/// <param name="selectName">所选数据的ID,用于查询指定的树节点</param>
public static void InsertTreeNode(TreeView treeview, TreeNode parenTn, TreeNode newTn, string nodeText, int id, string selectName)
{
int ok = 0; //0代表还没找到节点,1为找到节点
TreeNode selectedNode;
newTn = new TreeNode(nodeText);
newTn.Name = id.ToString();
if (selectName != "")
{
for (int i = 0; i < treeview.Nodes.Count; i++)
{
parenTn = treeview.Nodes[i];
for (int j = 0; j < parenTn.Nodes.Count; j++)
{
if (parenTn.Nodes[j].Name == selectName)
{
selectedNode = parenTn.Nodes[j];
selectedNode.Nodes.Add(newTn);
ok = 1;
break;
}
}
if (ok == 1)
{
break;
}
}
}
else
{
treeview.Nodes.Add(newTn);
}
}
public static void InsertTreeNode(TreeView treeview, TreeNode parenTn, string nodeText, int id, string selectName)
{
int ok = 0; //0代表还没找到节点,1为找到节点
TreeNode selectedNode;
parenTn = new TreeNode(nodeText);
parenTn.Name = id.ToString();
if (selectName != "")
{
for (int j = 0; j < treeview.Nodes.Count; j++)
{
if (treeview.Nodes[j].Name == selectName)
{
selectedNode = treeview.Nodes[j];
selectedNode.Nodes.Add(parenTn);
ok = 1;
break;
}
}
}
}
/// <summary>
/// 添加数据到数据库的同时把数据添加到指定的树节点
/// </summary>
/// <param name="parenTn">父节点</param>
/// <param name="newTn">新节点</param>
/// <param name="nodeText">新节点显示文本</param>
/// <param name="id">新接点唯一值,数据表中的ID</param>
/// <param name="selectName">所选数据的ID,用于查询指定的树节点</param>
public static void DirectInsertTreeNode(TreeNode parenTn, TreeNode newTn, string nodeText, int id)
{
newTn = new TreeNode(nodeText);
newTn.Name = id.ToString();
parenTn.Nodes.Add(newTn);
}
}
}