VB 获取动态创建的 ToolStrip 项的 select 的索引

VB Get index of select of dynamically created ToolStrip item

我已经有一段时间没有在 VB 中编程了,所以我有点生疏了。

我正在阅读 XML,其中包含项目列表。当我加载我的表单时,我用项目名称填充了一个工具条菜单(以及一个工作正常的组合框)。我还使用 "Edit" 和 "Delete" 动态填充每个项目的子菜单。我需要获取所选项目的索引,以便调用特定代码进行编辑和删除。我不太确定该怎么做。

代码如下:

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

回答你的问题:

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