Click here to Skip to main content
15,563,049 members
Please Sign up or sign in to vote.
4.67/5 (3 votes)
See more:
I am trying to create toolstrip buttons based on the contents of a folder what I have so far is this:
//Collect list of files<br />
            string dir = "C:\\Documents and Settings\\Herr Xandor\\Desktop\\Toolbar";<br />
            string[] files = System.IO.Directory.GetFiles(dir);<br />
            //Format string array<br />
            int x = 0;<br />
            int index = 0;<br />
            foreach (string temp in files)<br />
            {<br />
                index = temp.LastIndexOf('\\');<br />
                files[x] = temp.Substring(index + 1);<br />
                x += 1;<br />
            }<br />


My question is, how can I create buttons based on the contents of the array. I understand that I need another foreach loop that runs the necessary commands for each button but how can I control the naming and the onClick methods? I know of no way to use a variable to name an object. I'm pretty sure I can get it to create the buttons by using an array of buttons, but then how can I create the event handlers?
Posted

using System;
using System.IO;
using System.Windows.Forms;
namespace DynamicToolStrip
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DynamicToolStripForm());
        }
        class DynamicToolStripForm : Form
        {
            ToolStrip m_toolstrip = new ToolStrip();
            public DynamicToolStripForm()
            {
                Controls.Add(m_toolstrip);
                AddToolStripButtons();
            }
            void AddToolStripButtons()
            {
                const int iMAX_FILES = 5;
                string[] astrFiles = Directory.GetFiles(@"C:\");
                for (int i = 0; i < iMAX_FILES; i++)
                {
                    string strFile = astrFiles[i];
                    ToolStripButton tsb = new ToolStripButton();
                    tsb.Text = Path.GetFileName(strFile);
                    tsb.Tag = strFile;
                    tsb.Click += new EventHandler(tsb_Click);
                    m_toolstrip.Items.Add(tsb);
                }
            }
            void tsb_Click(object sender, EventArgs e)
            {
                ToolStripButton tsb = sender as ToolStripButton;
                if (tsb != null && tsb.Tag != null)
                    MessageBox.Show(String.Format("Hello im the {0} button", tsb.Tag.ToString()));
            }
        }
    }
}
 
Share this answer
 
This [^] thread might help.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900