下面的这段代码既实现了无限级
private void Load_TreeView(int ParentID, TreeNode pNode)
{
DataSet ds = new DataSet();
// 定义数据库连接
SqlConnection CN = new SqlConnection();
try
{
//初始化连接字符串
CN.ConnectionString = "Data Source=192.168.24.220;Integrated Security=SSPI;" + "Initial Catalog=LightCtrDB";
CN.Open();
//添加命令,从数据库中得到数据
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = CN;
sqlCmd.CommandText = "select * from Table2";
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(sqlCmd);
adp.Fill(ds);
}
catch (Exception ex)
{
throw (ex);
}
finally
{
CN.Close();
}
DataView dvTree = new DataView(ds.Tables[0]);
//过滤ParentID,得到当前的所有子节点
dvTree.RowFilter = "[PARENTID] = " + ParentID;
ArrayList Document = new ArrayList();
foreach (DataRowView Row in dvTree)
{
if (pNode == null)
{
TreeNode Node = treeView1.Nodes.Add(Row["ConText"].ToString());
Load_TreeView(Int32.Parse(Row["ID"].ToString()), Node); //再次递归
}
else
{ //添加当前节点的子节点
TreeNode Node = pNode.Nodes.Add(Row["ConText"].ToString());
Document.Add(new ListViewItem(Row["ConText"].ToString(), 2));
pNode.Tag = Document;
Load_TreeView(Int32.Parse(Row["ID"].ToString()), Node); //再次递归
}
}
treeView1.ImageList = imageList1;
}
private void Load_TreeView(int ParentID, TreeNode pNode)
{
DataSet ds = new DataSet();
// 定义数据库连接
SqlConnection CN = new SqlConnection();
try
{
//初始化连接字符串
CN.ConnectionString = "Data Source=192.168.24.220;Integrated Security=SSPI;" + "Initial Catalog=LightCtrDB";
CN.Open();
//添加命令,从数据库中得到数据
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = CN;
sqlCmd.CommandText = "select * from Table2";
sqlCmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter(sqlCmd);
adp.Fill(ds);
}
catch (Exception ex)
{
throw (ex);
}
finally
{
CN.Close();
}
DataView dvTree = new DataView(ds.Tables[0]);
//过滤ParentID,得到当前的所有子节点
dvTree.RowFilter = "[PARENTID] = " + ParentID;
ArrayList Document = new ArrayList();
foreach (DataRowView Row in dvTree)
{
if (pNode == null)
{
TreeNode Node = treeView1.Nodes.Add(Row["ConText"].ToString());
Load_TreeView(Int32.Parse(Row["ID"].ToString()), Node); //再次递归
}
else
{ //添加当前节点的子节点
TreeNode Node = pNode.Nodes.Add(Row["ConText"].ToString());
Document.Add(new ListViewItem(Row["ConText"].ToString(), 2));
pNode.Tag = Document;
Load_TreeView(Int32.Parse(Row["ID"].ToString()), Node); //再次递归
}
}
treeView1.ImageList = imageList1;
}