封装成一个函数,方便直接调用
//绑定TrreView
private void InitModuleTree(DataTable dt)
{
//清空treeview上所有节点
this.tree_Role.Nodes.Clear();
int[] gen = new int[dt.Rows.Count]; //用于存储父节点Tag
int[] zi = new int[dt.Rows.Count]; //用于存储子节点Tag
for (int i = 0; i < gen.Length; i++)
{
string zhi=dt.Rows[i][3].ToString();//获取节点Tag值 eg:1-2
if (zhi.Length>1) //表示是子节点 eg:1-2
{
gen[i] = int.Parse(zhi.Substring(0, zhi.IndexOf('-')));
zi[i] = int.Parse(zhi.Substring(zhi.IndexOf('-') + 1));
}
else //表示是根节点 eg:2
{
//将所有父节点加到treeview上
zi[i] =int.Parse(zhi);
TreeNode nodeParent = new TreeNode();
nodeParent.Tag = (zi[i]).ToString();
nodeParent.Text = dt.Rows[i][1].ToString();
tree_Role.Nodes.Add(nodeParent);
}
}
bindChildNote(dt,gen,zi);
}
//绑定子节点
private void bindChildNote(DataTable dt, int[] gen, int[] zi)
{
for (int i = 0; i < gen.Length; i++)
{
if (gen[i] != 0 && zi[i] != 0) //便利所有节点,找到所有子节点
{
TreeNode childNode = new TreeNode();
foreach (TreeNode item in tree_Role.Nodes) //便历treeview上所有父节点
{
if (item.Tag.ToString() == gen[i].ToString()) //找到当前子节点的父节点
{
childNode.Tag = zi[i].ToString();
childNode.Text = dt.Rows[i][1].ToString();
item.Nodes.Add(childNode);
}
}
}
}
tree_Role.ExpandAll(); //展开整棵树
}
数据库结构:
最终结果:
引用代码:
namespace TreeeeeeeeeeeView
{
public partial class Treeeeeeeeeee : Form
{
public Treeeeeeeeeee()
{
InitializeComponent();
//从数据库获取数据,得到结果为DataTable
SystemManager.Dao.RolePower dao = new SystemManager.Dao.RolePower();
DataSet ds = CommonLib.Dao.CompressUtil.DeCompress(dao.getSystemModule());
DataTable dt = ds.Tables[0];
InitModuleTree(dt);
}
//绑定TrreView
private void InitModuleTree(DataTable dt)
{
//清空treeview上所有节点
this.tree_Role.Nodes.Clear();
int[] gen = new int[dt.Rows.Count]; //用于存储父节点Tag
int[] zi = new int[dt.Rows.Count]; //用于存储子节点Tag
for (int i = 0; i < gen.Length; i++)
{
string zhi=dt.Rows[i][3].ToString();//获取节点Tag值 eg:1-2
if (zhi.Length>1) //表示是子节点 eg:1-2
{
gen[i] = int.Parse(zhi.Substring(0, zhi.IndexOf('-')));
zi[i] = int.Parse(zhi.Substring(zhi.IndexOf('-') + 1));
}
else //表示是根节点 eg:2
{
//将所有父节点加到treeview上
zi[i] =int.Parse(zhi);
TreeNode nodeParent = new TreeNode();
nodeParent.Tag = (zi[i]).ToString();
nodeParent.Text = dt.Rows[i][1].ToString();
tree_Role.Nodes.Add(nodeParent);
}
}
bindChildNote(dt,gen,zi);
}
//绑定子节点
private void bindChildNote(DataTable dt, int[] gen, int[] zi)
{
for (int i = 0; i < gen.Length; i++)
{
if (gen[i] != 0 && zi[i] != 0) //便利所有节点,找到所有子节点
{
TreeNode childNode = new TreeNode();
foreach (TreeNode item in tree_Role.Nodes) //便历treeview上所有父节点
{
if (item.Tag.ToString() == gen[i].ToString()) //找到当前子节点的父节点
{
childNode.Tag = zi[i].ToString();
childNode.Text = dt.Rows[i][1].ToString();
item.Nodes.Add(childNode);
}
}
}
}
tree_Role.ExpandAll(); //展开整棵树
}
}
}
以上就是C# TreeView从数据库绑定数据的示例的详细内容,更多关于C# TreeView从数据库绑定数据的资料请关注软件开发网其它相关文章!