项目中需要动态生成菜单,于是写了个简单的c#代码示例,有待进一步完善:

 

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("Code");
            dt.Rows.Add("1000");
            dt.Rows.Add("10001000");
            dt.Rows.Add("100010001000");
            dt.Rows.Add("100010001001");
            dt.Rows.Add("10001001");
            dt.Rows.Add("100010011000");
            dt.Rows.Add("100010011001");
            dt.Rows.Add("10001002");
            dt.Rows.Add("100010021000");
            dt.Rows.Add("100010021001");
            ds.Tables.Add(dt);

            for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
            {
                MenuItem mi = new MenuItem(ds.Tables[0].Rows[i][0].ToString(), ds.Tables[0].Rows[i][0].ToString(), "", "");
                for (int j = i+1; j < ds.Tables[0].Rows.Count; j++)
                {
                    if (ds.Tables[0].Rows[i][0].ToString().Length < ds.Tables[0].Rows[j][0].ToString().Length)
                    {
                        MenuItem mi1 = new MenuItem(ds.Tables[0].Rows[j][0].ToString(), ds.Tables[0].Rows[i][0].ToString(), "", "");
                        mi.ChildItems.Add(mi1);
                        if (j==ds.Tables[0].Rows.Count-1)
                        {
                            i = j;
                        }
                    }
                    else
                    {
                        i = j - 1;
                        break;
                    }
                }
                Menu1.Items.Add(mi);
            }

posted on 2009-05-06 22:04  Machine Lee  阅读(456)  评论(1编辑  收藏  举报