日期:2014-05-18 浏览次数:20760 次
private void bindTreeView1() { string sql = "select * from dm_category"; DataTable dt = db.ExecuteDataTable(sql, CommandType.Text, null); DataRow[] dr = dt.Select("parent_id is null"); for (int i = 0; i < dr.Length; i++) { TreeNode tn = new TreeNode(); tn.Text = dr[i]["category_name"].ToString(); tn.Tag = dr[i]["id"].ToString(); if (dr[i]["parent_id"].ToString() == "") { FillTree(tn, dt); tn.ImageIndex = 0; } treeView1.Nodes.Add(tn); } } private void FillTree(TreeNode node, DataTable dt) { DataRow[] drr = dt.Select("parent_id='" + node.Tag.ToString() + "'"); if (drr.Length > 0) { for (int i = 0; i < drr.Length; i++) { TreeNode tnn = new TreeNode(); tnn.Text = drr[i]["category_name"].ToString(); tnn.Tag = drr[i]["id"].ToString(); if (drr[i]["parent_id"].ToString() == node.Tag.ToString()) { FillTree(tnn, dt); tnn.ImageIndex = 1; } node.Nodes.Add(tnn); } } }
------解决方案--------------------
// 查询 using (var conn = new SqlConnection(连接字符串)) using (var ada = new SqlDataAdapter()) { conn.Open(); ada.SelectCommand.CommandText = "select m_orgid, m_name, m_UpdateName from 表名"; var dtbl = new DataTable(); ada.Fill(dtbl); Bind(null, dtbl, treeView.Nodes); } // 绑定方法 private static void Bind(string p, DataTable dtbl, TreeNodeCollection c) { var drws = dtbl.Select("m_UpdateName" + (p != null ? ("=" + p) : " is null")); foreach (var drw in drws) { var n = new TreeNode((string)drw[1]); n.Tag = drw; c.Add(n); Bind((string)drw[2], dtbl, n.Nodes); } }