我正在尝试使用C#WinForm项目创建动态菜单。我的数据库结构如下所述。我可以创建顶级菜单,即“FILE”,“EDIT”,“SEARCH”。但我不能运行子菜单的递归功能。
mysql> select * from dynamicmenu;
+------+-----------------+--------+-------+-----------+
| SLN | Child | Parent | Level | Reference |
+------+-----------------+--------+-------+-----------+
| 1 | FILE | NULL | 0 | NULL |
| 2 | EDIT | NULL | 0 | NULL |
| 3 | SEARCH | NULL | 0 | NULL |
| 4 | Session Manager | FILE | 1 | 1 |
| 5 | Connect To | FILE | 1 | 1 |
| 6 | DO | FILE | 2 | 5 |
| 7 | Copy | EDIT | 1 | 2 |
| 8 | Paste | EDIT | 1 | 2 |
| 9 | Find Text | SEARCH | 1 | 3 |
| 10 | Cut | EDIT | 2 | 7 |
| 11 | VMS | FILE | 3 | 6 |
+------+-----------------+--------+-------+-----------+
11 rows in set (0.00 sec)
c#代码如下。
mysqlConn conn;
private void Form1_Load(object sender, EventArgs e)
{
conn = new mysqlConn();
conn.OpenConnection();
MySqlCommand cmd = new MySqlCommand("Select * from dynamicmenu", conn.connection);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["Parent"].ToString() == "")
{
menuStrip1.Items.Add(dr["Child"].ToString());
}
else if (dr["Parent"].ToString() != "")
{
AddSubMenu(new ToolStripMenuItem(dr["Child"].ToString()), dr["Parent"].ToString());
}
}
dr.Close();
conn.CloseConnection();
}
private void AddSubMenu(ToolStripMenuItem ChildItem, string ParentItem)
{
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (ParentItem == item.Name)
{
item.DropDownItems.Add(ChildItem);
}
}
}
请告知。
答案 0 :(得分:0)
使用toString()
代替name
。
private void AddSubMenu(ToolStripMenuItem ChildItem, string ParentItem)
{
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
if (ParentItem == item.ToString())
{
item.DropDownItems.Add(ChildItem);
}
}
}