当前位置:编程学习 > C#/ASP.NET >>

asp.net关于Treeview

这是我找到的一些代码,可写到程序里每新增一个父节点,显示出来的却是相同名称的父节点和子节点,并且不能新增子节点,(如:新增Hello父节点,显示出来的是+--Hello
---Hello);请各位大大帮忙修改一下,能实现新增父节点和子节点并显示正常,谢谢了!

protected void Page_Load(object sender, EventArgs e)
{
objMyconn.CobjMyconn.ConnectionString = "Pooling=true;Password=123;Persist Security Info=True;User ID=sa;Initial Catalog=rocflyhrm;Data Source=192.168.1.10";
objMyconn.Open();
if (!IsPostBack)
{

DataView DView = dv("select * from sys_departments");
foreach (DataRowView drv in DView)
{

TreeNode tn = new TreeNode();
tn.Text = drv["dept_name"].ToString();
tn.Value = drv["dept_id"].ToString();
tn.Expanded = false;
TreeView1.Nodes.Add(tn);
AddchildNode(tn);
}
BindData();

}
if (TreeView1.Nodes.Count == 0)
{
Button2.Enabled = false;
}



}


private void AddchildNode(TreeNode tn)
{
string id = tn.Value.ToString();
DataView dView = dv("select * from sys_departments where dept_id='"+id+"'");

foreach (DataRowView drv2 in dView)
{
TreeNode ctn = new TreeNode();
ctn.Text = drv2["dept_name"].ToString();
ctn.Value = drv2["dept_id"].ToString();
tn.ChildNodes.Add(ctn);
}
}

private DataView dv(string str)
{
string mycon = ConfigurationManager.ConnectionStrings["rocflyhrmConnectionString"].ToString();
SqlConnection con = new SqlConnection(mycon);
SqlDataAdapter da = new SqlDataAdapte
答案:
{
TreeView1.Nodes.Clear();

DataTable dt = tree_table();
DataView dv = new DataView(dt);
dv.RowFilter = "dept_id = 0";

foreach (DataRowView drv in dv)
{
TreeNode node = new TreeNode();
node.Text = drv["dept_name"].ToString();
node.Value = drv["dept_id"].ToString();
node.NavigateUrl = "Default.aspx";
Session["dept_id"] = drv["dept_id"];

TreeView1.Nodes.Add(node);
AddChildNode(dt, node);
}
}
private DataTable tree_table()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rocflyhrmConnectionString"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter("select * from sys_departments", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
private void AddChildNode(DataTable dt, TreeNode node)
{
DataView dv = new DataView(dt);
dv.RowFilter = "dept_up_id='" + node.Value + "'";
foreach (DataRowView drv1 in dv)
{
TreeNode ChildNode = new TreeNode();
ChildNode.Text = drv1["dept_name"].ToString();
ChildNode.Value = drv1["dept_id"].ToString();
ChildNode.Expanded = false;

node.ChildNodes.Add(ChildNode);

AddChildNode(dt, ChildNode);
}
}
晕 ,给你个思路 数据库  int id当前节点的ID,varchar nodeName节点的文本内容,int Pid 父节点的ID
这样 ,你查询的时候 要默认的 传2个参数进行查询 TreeNode node 和Pid
SQL语句为 Select * from 表 where pid = Pid ;
Page_Load 中 自己先创建一个根节点 然后讲 node 传到 绑定方法里面
绑定的方法(TreeNode node,int Pid)
代码基本和 AddchildNode 一样,需要多传一个Pid 的参数
在 foreach 的最后添加一行代码 AddchildNode(ctn ,pid)
用 递归算法 来绑定树

上一个:在asp.net中
下一个:asp.net高手救急!!!

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,