简体   繁体   中英

How to Programmatically add a ToolstripDropDownButton to a toolstrip with dropdown menu (C# Winforms)

I have a toolstrip that will contain toolstripdropdownbuttons that represent folders that are found in a directory. I would like a dropdown menu to each toolstripdropdownbutton to contain subfolders that are found. An example of this would be the Internet Explorer Links bar I have tried the following code but I'm not quite sure how to go about it (see picture) Links Bar Example

Code I have tried:

        private void populateLinks()
    {
        linksToolStrip.Items.Clear();
        DirectoryInfo linksFolder = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Favorites) + "\\Links");
        foreach (DirectoryInfo linksDirectory in linksFolder.GetDirectories())
        {
            Image favImage = Properties.Resources.Folder;
            ToolStripDropDownButton button = new ToolStripDropDownButton();
            button.Text = Truncate(linksDirectory.Name, 22);
            button.ToolTipText = linksDirectory.Name + "\nDate Created: " + Directory.GetCreationTime(linksDirectory.FullName);
            button.Image = favImage;
            button.Tag = linksDirectory.FullName;
            linksToolStrip.Items.Add(button);
            populateLinksFolders(linksDirectory, button.DropDown);

        }

and

private void populateLinksFolders(DirectoryInfo subdirectory, ToolStripDropDown tsdd)
    {
        foreach (DirectoryInfo directory in subdirectory.GetDirectories())
        {
            populateLinksFolders(directory, ?) //<- Everything tried here fails
        }
    }

How can I accomplish this?

You need to pass the ToolStripDropDownButton , then use the DropDownItems property to add subitems.

populateLinksFolders(linksDirectory, button);

Then:

private void populateLinksFolders(DirectoryInfo subdirectory, ToolStripDropDownButton tsddb)
{
    foreach (DirectoryInfo directory in subdirectory.GetDirectories())
    {
        ToolStripDropDownButton button = new ToolStripDropDownButton(directory.Name);
        tsddb.DropDownItems.Add(button);
        populateLinksFolders(directory, button);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM