圣诞快乐!总算弄出来了。 public partial class MainWindow : Window { public MainWindow() { InitializeComponent();
string conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\WpfTest\WpfTest\Database1.mdf;Integrated Security=True;User Instance=True"; SqlConnection con = new SqlConnection(conStr); con.Open(); SqlCommand com = con.CreateCommand(); com.CommandText = "select id,deptname,parentid from depttest1"; SqlDataReader reader = com.ExecuteReader(); List nodes = new List(); int i=0; while (reader.Read()) {
Node partyGroup = new Node(); partyGroup.ID = reader["id"].ToString(); partyGroup.Name = reader["deptname"].ToString(); if (reader["parentid"].ToString() != "") { partyGroup.ParentID = reader["parentid"].ToString(); }
i++; nodes.Add(partyGroup); }
List outputList = Bind(nodes); this.TreeView1.ItemsSource = outputList; }
#region 绑定科室类 List Bind(List nodes) { List outputList = new List(); for (int i = 0; i < nodes.Count; i++) { if (nodes[i].ParentID == "-1") outputList.Add(nodes[i]); else FindDownward(nodes, nodes[i].ParentID).Nodes.Add(nodes[i]); } return outputList; } #endregion #region 查找父级节点 Node FindDownward(List nodes, string id) { if (nodes == null) return null; for (int i = 0; i < nodes.Count; i++) { if (nodes[i].ID == id) return nodes[i]; Node node = FindDownward(nodes[i].Nodes, id); if (node != null) return node; } return null; } #endregion private void button1_Click(object sender, RoutedEventArgs e) { Node node=(Node)TreeView1.SelectedItem; MessageBox.Show(node.ID.ToString(), node.Name); }