怎么样利用.net 2.0中的TreeView控件与数据库绑定生成无限的树目录?
数据表的结构

usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.Data.SqlClient;
publicpartialclass_Default:System.Web.UI.Page


{
protectedstring_connstr=ConfigurationManager.ConnectionStrings["DemoConnectionstrings"].ConnectionString;
protectedvoidPage_Load(objectsender,EventArgse)


{
if(!Page.IsPostBack)


{
BindTree();
using(SqlConnection_conn=newSqlConnection(_connstr))


{
SqlCommand_comm=newSqlCommand("select*fromtreeview",_conn);

_conn.Open();
using(SqlDataReaderr=_comm.ExecuteReader())


{
while(r.Read())


{
ListItemitem=newListItem(r["txt"].ToString(),r["id"].ToString());
this._dd_parent.Items.Add(item);
}
}
}
this._dd_parent.Items.Insert(0,newListItem("
.","0"));
}
}
protectedvoidBindTree()


{
TreeNodenode=newTreeNode();//这里是创建一个根节点,就是dome中看到的Root
node.Text="Root";
CreateChildTree(node,0);
_tree_view.Nodes.Add(node);
}

protectedvoidCreateChildTree(TreeNode_parentNode,int_parentID)


{
using(SqlConnection_conn=newSqlConnection(_connstr))


{
SqlCommand_comm=newSqlCommand();
stringsql="select*fromtreeviewwhererootid=@rootid";
_comm.Parameters.Add("@rootid",SqlDbType.Int).Value=_parentID;
_comm.CommandText=sql;
_comm.Connection=_conn;
_conn.Open();
using(SqlDataReaderr=_comm.ExecuteReader())


{
while(r.Read())


{
TreeNode_node=newTreeNode(r["txt"].ToString());
CreateChildTree(_node,(int)r["ID"]);//递归出子节点
_parentNode.ChildNodes.Add(_node);
}
}
}
}
protectedvoid_btn_submit_Click(objectsender,EventArgse)


{
int_rootid=Convert.ToInt16(this._dd_parent.SelectedValue);
string_txt=this._txt_txt.Text.Trim();
using(SqlConnection_conn=newSqlConnection(_connstr))


{
SqlCommand_comm=newSqlCommand("insertintotreeview(txt,rootid)values(@txt,@id)",_conn);
_comm.Parameters.Add("@txt",SqlDbType.VarChar,50).Value=_txt;
_comm.Parameters.Add("@id",SqlDbType.Int).Value=_rootid;
_conn.Open();
_comm.ExecuteNonQuery();
}
this._tree_view.Nodes.Clear();
BindTree();
}
}
本文地址:
http://www.45fan.com/a/question/69218.html