网站中用treeview管理无穷级别
一、先看看下面的建库方法Class_ID(自动编号) Class_Name(类别名称) parent_ID(父节点编号)
1 新闻 0(根节点)
2 体育新闻 1
3 NBA新闻 2
4 足球 2
........
二、显示节点信息
public void Fun_Tree(TreeNode TREE)
{
try
{
DS = db.ExecuteDataSet("select * from Class");
DT = DS.Tables[0];
if (Tree_Node_P == false)
{
foreach (DataRow DR in DT.Rows)
{
if (!al.Contains(DR.ItemArray[1]))
{
if (DR.ItemArray[2].ToString() == "0")
{
al.Add(DR.ItemArray[1]);
al_BigClass_ID.Add(DR.ItemArray[0]);
}
}
}
for (int i = 0; i < al.Count; i++)
{
TreeNode TN = new TreeNode();
TN.Text = al[i].ToString();
TN.Value = al_BigClass_ID[i].ToString();
string select1 = "select Class_ID,Class_Name from Class where Class_Name='" + al[i].ToString() + "'";
DS = db.ExecuteDataSet(select1);
TN.Text = DS.Tables[0].Rows[0][1].ToString();
TN.Value = DS.Tables[0].Rows[0][0].ToString();
TREE.ChildNodes.Add(TN);
}
Tree_Node_P = true;
}
foreach (DataRow DR_2 in DT.Rows)
{
foreach (TreeNode TN_2 in TREE.ChildNodes)
{
if (DR_2.ItemArray[2].ToString() == TN_2.Value.ToString())
{
TreeNode TN_3 = new TreeNode();
TN_3.Text = DR_2.ItemArray[1].ToString();
string select1 = "select Class_ID,Class_Name from Class where Class_Name='" + DR_2.ItemArray[1].ToString() + "'";
DS = db.ExecuteDataSet(select1);
TN_3.Text = DS.Tables[0].Rows[0][1].ToString();
TN_3.Value = DS.Tables[0].Rows[0][0].ToString();
TN_2.ChildNodes.Add(TN_3);
Fun_Tree_2(TN_3);
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
#region [函数] [树型>3级递归]
public void Fun_Tree_2(TreeNode T_Name)
{
foreach (DataRow DR_2 in DT.Rows)
{
if (DR_2.ItemArray[2].ToString() == T_Name.Value.ToString())
{
TreeNode TN_3 = new TreeNode();
TN_3.Text = DR_2.ItemArray[1].ToString();
TN_3.Value = DR_2.ItemArray[0].ToString();
T_Name.ChildNodes.Add(TN_3);
Fun_Tree_2(TN_3);
}
}
}
#endregion
三、添 if (this.TreeView1.CheckedNodes.Count < 0)
{
Response.Write("<script language='javascript'>alert('你没有选中节点!请重新选择!');</script>");
return;
}
if (this.TreeView1.CheckedNodes.Count > 1)
{
Response.Write("<script language='javascript'>alert('你选中了两个以上的节点!请重新选择!');</script>");
return;
}
TreeNode newNode = new TreeNode(this.TextBox1.Text, "0");
foreach(TreeNode tn in TreeView1.CheckedNodes)
{
if (tn.Checked == true)
{
tn.ChildNodes.Add(newNode);
tn.Expand();
if (tn.Text == "所有类别")
{
string mycommand = "insert into BigClass values('" + newNode.Text + "',0)";
db.ExecuteNonQuery(mycommand);
}
else
{
string mycommand = "insert into BigClass(BigClass_Name,parent_ID) values('" + newNode.Text + "'," + Convert.ToInt32(tn.Value) + ")";
db.ExecuteNonQuery(mycommand);
}
}
}
this.TreeView1.ExpandAll();
this.TextBox1.Text = "";
加节点
" border="0" />