private void BindTreeView()
{
//创建代表省市地区的三个节点
TreeNode parentnode;
TreeNode childnode;
TreeNode townnode;
string constr = "Data Source=(Local);Database=yang;uid=sa;pwd=sa";
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from province",con);
DataSet ds = new DataSet();
da.Fill(ds,"sheng");
foreach(DataRow parentrow in ds.Tables["sheng"].Rows)
{
//实例化省节点,第一个参数是节点显示的名称,第二个是对应的ID值(不显示的),第三个是ImageList图片中的图片的索引值
parentnode = new TreeNode(parentrow["name"].ToString(),Convert.ToInt32(parentrow["code"].ToString()),1);
//将节点添加到树上咯
treeView1.Nodes.Add(parentnode);
//查找该省对应有没有市
SqlDataAdapter da2 = new SqlDataAdapter("select * from city where provinceId='"+parentrow["code"].ToString()+"'",con);
DataSet ds2 = new DataSet();
da2.Fill(ds2,"shi");
if(ds2.Tables["shi"].Rows.Count>0)
{
foreach(DataRow childrow in ds2.Tables["shi"].Rows)
{
childnode = new TreeNode(childrow["name"].ToString(),Convert.ToInt32(childrow["code"].ToString()),2);
//将对应的市添加到该省的节点下
parentnode.Nodes.Add(childnode);
//查找该市对应有没有地区
SqlDataAdapter da3 = new SqlDataAdapter("select * from area where cityId='"+childrow["code"].ToString()+"'",con);
DataSet ds3 = new DataSet();
da3.Fill(ds3,"diqu");
if(ds3.Tables["diqu"].Rows.Count>0)
{
foreach (DataRow diqurow in ds3.Tables["diqu"].Rows)
{
townnode = new TreeNode(diqurow["name"].ToString(),Convert.ToInt32(diqurow["code"].ToString ()),3);
//将对应的地区添加到该市节点下
childnode.Nodes.Add(townnode);
}
ds3.Tables["diqu"].Clear();
}
}
ds2.Tables["shi"].Clear();
}
}
}