我想我会再试一次这个地方的答案。 我有这个代码加载C:\ Quiz
中的文件夹名称For Each dir As String In Directory.GetDirectories("C:\Quiz")
Dim dirinfo As New DirectoryInfo(dir)
MenuStrip1.Items.Add(dirinfo.Name) ' loads the folder names
For Each fn As String In Directory.GetFiles(dir) ' get the txt files in the directory Quiz's subfolders
Next
我不确定如何为menustrip.item创建toolstripmenuitem对象,并将每个文件夹中的测验问题加载到他们的透视图menustrip.item名称
子菜单将在运行时加载。这是我尝试过的但无济于事:
'iterate through each file in the current directory (dir)
For Each fn As String In Directory.GetFiles(dir)
'add the file name without the extension to a new ToolStripMenuItem
Dim menuItem As New ToolStripMenuItem(IO.Path.GetFileNameWithoutExtension(fn))
'set the Tag of the new ToolStripMenuItem to the full path and name of the file
menuItem.Tag = fn
'add the new ToolStripMenuItem to your existing (DropDownButton) in the ToolStrip or your (MenuItem) in your MenuStrip
MenuStrip1.Add(menuItem)
这不会填充每个菜单子菜单,整个想法是在运行时使用C:\ Quiz中的文件夹名称和每个文件夹中的文本文件填充菜单和子菜单: C:\ Quiz \ Genesis \ Genesis1.txt,2.txt .... C:\ Quiz \ Exodus \ Exodus1.txt,2.txt ....依此类推。我很感激这方面的帮助,因为我还在学习,并且已经在这里工作了很长一段时间。谢谢
答案 0 :(得分:1)
Private Sub LoadFile(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'iterate through each directory in the C:\Quiz folder
For Each dir As String In Directory.GetDirectories("C:\Quiz")
'add the current folder name to a new ToolStripMenuItem
Dim mainMenuItem As New ToolStripMenuItem(IO.Path.GetFileName(dir).Substring(2))
'add the new ToolStripMenuItem to the ToolStrip
MenuStrip1.Items.Add(mainMenuItem)
'iterate through each file in the current directory (dir)
For Each fn As String In Directory.GetFiles(dir)
'add the current file name without the extension to a new ToolStripMenuItem
Dim subMenuItem As New ToolStripMenuItem(IO.Path.GetFileNameWithoutExtension(fn))
'set the Tag of the new ToolStripMenuItem to the full path and name of the file
subMenuItem.Tag = fn
'add the new ToolStripMenuItem to the DropDownItems of the (folder) ToolStripMenuItem
mainMenuItem.DropDownItems.Add(subMenuItem)
'add the QuizItem_Click handler sub to to the new ToolStripMenuItem
AddHandler subMenuItem.Click, AddressOf QuizItem_Click
Next
Next
End Sub
Private Sub QuizItem_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'cast the "sender" to a ToolStripMenuItem
Dim tsmi As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
'convert the Tag (Object) back to a string to get the full file path name from the ToolStripMenuItem that was clicked
Dim FileToLoad As String = tsmi.Tag.ToString
'just to show you the full file path and name from the ToolStripMenuItem Tag
MessageBox.Show("You want to load this file" & vbNewLine & FileToLoad)
End Sub
感谢IronRazer和CharlieMay!