费话不多讲,先设计数据库简单点:
id,menu_name,parent_id,level,menu_link,其中parent_id是基于父节点menu_name的子节点,所以看parent-id对照menu-name就知道父节点了,后有应用例子
cs代码:
Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
TreeView_root_load();
TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
TreeView1.Attributes.Add("onclick", "postBackByObject()"); //注册客户端事件
}
}
当然要声明函数啦,有些人取数据用dataview,我暂时还不很习惯,我用DataTable
private void TreeView_root_load()//根入先
{
DataTable get_site_menu = dbcenter.accessGetDataSet("select * from menu_site where level='0'").Tables[0];//得到表的数据集
for (int i = 0; i <= get_site_menu.Rows.Count - 1; i++)
{
TreeNode node = new TreeNode();
node.Text = get_site_menu.Rows[i]["menu_name"].ToString();
TreeView1.Nodes.Add(node);
node.SelectAction = TreeNodeSelectAction.Expand;//不导航
AddChildNodes(node);//递归入
}
}
private void AddChildNodes(TreeNode ChildNode)
{
string parent_id = ChildNode.Value.ToString();
DataTable get_site_menu_child = dbcenter.accessGetDataSet("select * from menu_site where parent_id='" + parent_id + "'").Tables[0];//得到子的数据集
for (int j = 0; j <= get_site_menu_child.Rows.Count - 1; j++)
{
TreeNode node = new TreeNode();
node.Text = get_site_menu_child.Rows[j]["menu_name"].ToString();
ChildNode.ChildNodes.Add(node);
node.SelectAction = TreeNodeSelectAction.Expand;
AddChildNodes(node);
}
}
//在数据库中删除,先删根,再删子节点,目前支持两级,可以开发为递归删除子节点
开始时候定义好
public static string tmp_node_text ;
而且在选定节点时候回发,接收到选定的tmp_node ,参考上一篇blog,tmp_node为选定的节点
TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
tmp_node_text = e.Node.Text;
tmp_node = e.Node;
}
tmp_node_text 为选定的节点的属性在这里用到了
protected void Button10_Click(object sender, EventArgs e)//在数据库中删除
{
string sql_check_node = "select * from menu_site where menu_name='" + tmp_node .Text + "'";
if (tmp_node.Text != "" && dbcenter.accessGetDataSet(sql_check_node).Tables[0].Rows.Count > 0)
{
string sql_del_node="delete * from menu_site where menu_name='" + tmp_node .Text + "'";
string sql_del_node_2 = "delete * from menu_site where parent_id='" + dbcenter .accessGetDataSet (sql_check_node ).Tables [0].Rows[0]["menu_name"].ToString() + "'";
OleDbConnection conn = dbcenter.Acce_Conn();
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql_del_node, conn);//删根
cmd.ExecuteNonQuery();
OleDbCommand cmd2 = new OleDbCommand(sql_del_node_2 , conn);//删子
cmd2.ExecuteNonQuery();
conn.Close();
}
Response.Redirect("site_install_01.aspx");//一定要本页刷新,否则不出效果
}
到增加节点的环节了
protected void Button8_Click(object sender, EventArgs e)
{
string sql_check_node = "select * from menu_site where menu_name='"+TextBox46 .Text +"'";
if (TextBox46.Text != "" && dbcenter.accessGetDataSet(sql_check_node).Tables[0].Rows.Count ==0)//如果数据库中没有该节点,则增加
{
TreeNode tm_node = new TreeNode();
tm_node.Text = TextBox46.Text;
TreeView1.Nodes.Add(tm_node);
//写入库代码省略...
}
else
{
Response.Write("<script language=javascript>alert('节点不能为空或者不能与已有节点冲突')</script>");
}
}
好了,总结一下,原来treeview这么多东西要研究,真是不简单啊。我有两天研究没有一点进展,总是闷闷不乐,不过幸好有研究的兴趣,又终于有小小突破啦.快学习啊。要不,真是很落后噶啦.!!!