form1
public void treeView() { // datatable 定义变量接收 传归来的值 DataTable Father = new BuMenDA().ConSql(); //查询出来的的结果不可能为空 for循环一条条查出来 for (int a = 0; a <= Father.Rows.Count; a++) {// 定义新的节点接a行的 Name列 TreeNode fatherNode = new TreeNode(Father.Rows[a]["Name"].ToString()); //给节点添加数据源 fatherNode.Tag = Father.Rows[a]["Name"].ToString(); // 绑定节点的Name值 Code 以便以后使用 fatherNode.Name = Father.Rows[a]["Code"].ToString(); treeView1.Nodes.Add(fatherNode); //添加父节点 //根据节点的 Name 查询另一个表的数据 DataTable child = new BuMenDA().ConSql1(int.Parse(fatherNode.Name)); //再次循环 for (int b = 0; b < child.Rows.Count; b++) { //同上 建立新的节点接收传过来值 TreeNode ChildNode = new TreeNode(child.Rows[b]["Name"].ToString()); //绑定数据源 ChildNode.Tag = child; //在添加父节点的基础上添加子节点 fatherNode.Nodes.Add(ChildNode); } } } private void Form1_Load(object sender, EventArgs e) { treeView(); }
UseDA
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data.Sql; using System.Data; namespace ListViewAdd.UseDA { class BuMenDA { private string conn() { return "Server=.;Database=BuMen;User ID=sa;Password=123"; } //查询第一个表的数据 public DataTable ConSql() { string sql = "select * from BuMenShow"; SqlConnection MyCon = new SqlConnection(conn()); MyCon.Open(); SqlDataAdapter myda = new SqlDataAdapter(sql, conn()); DataSet MD = new DataSet(); myda.Fill(MD); return MD.Tables[0]; } //查询第二个表的数据 public DataTable ConSql1(int Code) { string sql = "select * from Member where MemCode =" + Code; SqlConnection MyCon = new SqlConnection(conn()); MyCon.Open(); SqlDataAdapter myda = new SqlDataAdapter(sql, conn()); DataSet MD = new DataSet(); myda.Fill(MD); return MD.Tables[0]; } } }