C# TreeView读取数据库简单实例

时间:2021-05-20

效果:

数据库:

思路:

利用for遍历,然后创建父节点,再根据父节点创建出子节点。

代码:
复制代码 代码如下:
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.Collections;
using System.Configuration;
using System.Data.SqlClient;

namespace TreeView
{
public partial class TreeView : System.Web.UI.Page
{
string connection = ConfigurationManager.ConnectionStrings["SQLconnection"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
select();
CreateTree();
}
DataSet ds = new DataSet();
public DataSet DataS(string sql, string tablename)
{
SqlConnection con = new SqlConnection(connection);
SqlDataAdapter sqlda = new SqlDataAdapter(sql, con);
sqlda.Fill(ds, tablename);
return ds;
}

//ParentMenu:父节点,
//Grade:标识这是第几级节点,
//Flag:标识是不是尾结点,1是 0 不是,
//href:指向的链接
public void select()
{
string sql = "select * from treeview";
ds = DataS(sql, "test");
}

public void CreateTree()
{
try
{
DataTable dt = ds.Tables["test"];
SortedList sl = new SortedList();
TreeNode tn = new TreeNode();
if (dt.Rows.Count <= 0)
{
tn.Text = "空";
tn.Value = "";
tn.NavigateUrl = "";
tn.Target = "";
tn.Expanded = false;
tn.SelectAction = TreeNodeSelectAction.SelectExpand;

}
else
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//创建父节点
if (dt.Rows[i]["Grade"].ToString() == "1")
{
TreeNode node = new TreeNode();
node.Text = dt.Rows[i]["MenuName"].ToString();
node.Value = dt.Rows[i]["MenuID"].ToString();
if (dt.Rows[i]["Flag"].ToString() == "1")
{
node.NavigateUrl = dt.Rows[i]["href"].ToString();
tn.Target = "_bank";
}
node.Expanded = false;
node.SelectAction = TreeNodeSelectAction.Expand;
sl.Add(node.Value, node);
tv_Method.Nodes.Add(node);
}
else
{
//查找父节点
TreeNode ParentNod = (TreeNode)sl.GetByIndex(sl.IndexOfKey(dt.Rows[i]["ParentMenu"].ToString()));
//创建子节点
TreeNode tnChild = new TreeNode();
tnChild.Text = dt.Rows[i]["MenuName"].ToString();
tnChild.Value = dt.Rows[i]["MenuID"].ToString();
if (dt.Rows[i]["Flag"].ToString() == "1")
{
tnChild.NavigateUrl = dt.Rows[i]["href"].ToString();
tnChild.Target = "_bank";
}
tnChild.Expanded = false;
tnChild.SelectAction = TreeNodeSelectAction.Expand;
sl.Add(tnChild.Value, tnChild);
ParentNod.ChildNodes.Add(tnChild);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章