树形菜单在平常的开发中是最常见的了,自已也练习练习,先来看两个图:
效果图 表结构
实现代码:
private void Form1_Load(object sender, EventArgs e)
{
this.BindTree(0);
}
private DataSet GetData(int pid)
{
string strCon = @"Data Source=Agony\SQLSERVER2005;Initial Catalog=sports;Integrated Security=True";
string sql = "SELECT * FROM sport WHERE pid=" + pid;
SqlConnection conn = new SqlConnection(strCon);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "sport");
return ds;
}
//绑定父节点
private void BindTree(int pid)
{
DataSet ds = GetData(pid);
if (ds.Tables["sport"].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables["sport"].Rows.Count; i++)
{
TreeNode node = new TreeNode();
node.Text = ds.Tables["sport"].Rows[i]["sname"].ToString();
node.Tag = ds.Tables["sport"].Rows[i]["id"].ToString();
this.treeView1.Nodes.Add(node);
BindChildNode(node);
}
}
}
//绑定子节点
private void BindChildNode(TreeNode node)
{
TreeNode tn = node;
int id = Convert.ToInt32(tn.Tag);
DataSet ds = GetData(id);
for (int i = 0; i < ds.Tables["sport"].Rows.Count; i++)
{
TreeNode nod = new TreeNode();
nod.Text = ds.Tables["sport"].Rows[i]["sname"].ToString();
nod.Tag = ds.Tables["sport"].Rows[i]["id"].ToString();
tn.Nodes.Add(nod);
BindChildNode(nod);
}
}