日期:2014-05-17 浏览次数:20798 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WinTest { public partial class Form1 : Form { DataTable dt; public Form1() { InitializeComponent(); dt = getdata(); } public DataTable getdata() { DataTable dt = new DataTable(); dt.Columns.Add("id"); dt.Columns.Add("parentID"); dt.Columns.Add("title"); Random rand = new Random(); for (int i = 0; i < 15; i++) { DataRow dr = dt.NewRow(); dr[0] = i + 1; dr[1] = (15 % (i + 1) == 0) ? "" : rand.Next(1, 10).ToString(); dr[2] = "name_" + (i + 1).ToString(); dt.Rows.Add(dr); } return dt; } private void button2_Click(object sender, EventArgs e) { DataRow[] drows = dt.Select("parentID=''"); if (drows.Length > 0) { foreach (DataRow item in drows) { ToolStripMenuItem toolitem = new ToolStripMenuItem(item["title"].ToString()); DataRow[] children = dt.Select(string.Format("parentID='{0}'", item["id"].ToString())); if (children.Length > 0) { bind(toolitem, item); } menuStrip2.Items.Add(toolitem); } } } private void bind(ToolStripMenuItem item,DataRow dr) { DataRow[] rows = dt.Select(string.Format("parentID='{0}'",dr["id"].ToString())); if (rows.Length > 0) { foreach (DataRow drv in rows) { bind(item,drv); } } else { item.DropDownItems.Add(dr["title"].ToString()); } } } }
------解决方案--------------------
上面的代码在构造DataTable的时候有问题,不好意思。请看下面的代码。这个是调试通过的。
private void button2_Click(object sender, EventArgs e) { InitTree(); } public void InitTree() { DataView dv = this.GetData(); dv.RowFilter = "ParentID=0"; foreach (DataRowView drv in dv) { ToolStripMenuItem node = new ToolStripMenuItem(); node.Text = drv["cname"].ToString(); this.menuStrip1.Items.Add(node); BuildTree(dv, node,drv["cid"].ToString()); } } private void BuildTree(DataView dv, ToolStripMenuItem pnode,string parentID) { dv.R