VB获取动态创建的ToolStrip项

时间:2015-08-07 14:37:00

标签: vb.net menuitem indexof selectedindex toolstrip

我还没有在VB中编程一段时间,所以我有点生气。

我有一个我正在阅读的XML,其中包含一个项目列表。当我加载表单时,我使用项目名称填充工具栏菜单(以及工作正常的组合框)。我还使用“编辑”和“删除”为每个项目动态填充子菜单。我需要获取所选项目的索引,以便我可以调用某些代码进行编辑和删除。我不太清楚如何做到这一点。

以下是代码:

Public Sub loadXML()
    ' Load the XML file.
    xml_doc.Load(Application.StartupPath & "\Settings.xml")

    ' Get the desired children.
    child_nodes = xml_doc.GetElementsByTagName("project")

    ' Fill the project combo box and to the project menu
    cmbProjects.Items.Clear()
    For Each child As System.Xml.XmlElement In child_nodes
        cmbProjects.Items.Add(child.SelectSingleNode("projectname").InnerText)
        Dim project As New ToolStripMenuItem(child.SelectSingleNode("projectname").InnerText)
        Dim edit As New ToolStripMenuItem("Edit")
        Dim delete As New ToolStripMenuItem("Delete")
        project.DropDownItems.Add(edit)
        project.DropDownItems.Add(delete)
        ProjectsMenu.DropDownItems.Add(project)
        AddHandler edit.Click, AddressOf editProject
        AddHandler delete.Click, AddressOf deleteProject

    Next

Private Sub editProject(ByVal sender As System.Object, ByVal e As System.EventArgs)
    MsgBox("Editing project...")
    ' Need to find the index of the project here so I can call the edit for that specific project
End Sub

Private Sub deleteProject(ByVal sender As System.Object, ByVal e As System.EventArgs)
    MsgBox("Deleting project...")
    ' Need to find the index of the project here so I can call the delete for that specific project
End Sub

1 个答案:

答案 0 :(得分:1)

按要求回答你的问题:

Dim child = DirectCast(sender, ToolStripMenuItem)
Dim parent = DirectCast(child.OwnerItem, ToolStripMenuItem)
Dim grandparent = DirectCast(parent.OwnerItem, ToolStripMenuItem)
Dim parentIndex = grandparent.DropDownItems.IndexOf(parent)