Valhalla Legends Archive

Programming => General Programming => .NET Platform => Topic started by: shout on May 24, 2006, 02:59 PM

Title: Dynamic Menus
Post by: shout on May 24, 2006, 02:59 PM
I have been trying to make a menu that has items based on how many of a certain type of file are found. I can make the menus, but when it comes time to set events to them I get stuck.

My current code:

mnu_textures = new MenuItem[files.Length];
for (int i = 0; i < files.Length; i++)
{
imglist.Images.Add(new Bitmap(files[i]));
mnu_textures[i] = new MenuItem();
mnu_textures[i].Index = i;
mnu_textures[i].Text = files[i].Split(new char[] {'_', '.', '\\'},100)
[files[i].Split(new char[] {'_', '.', '\\'}, 100).Length - 3];
mnu_textures[i].Click += new EventHandler(mnutextures_Click);
}
this.menuItem10.MenuItems.AddRange(mnu_textures);


I got to that, realized my problem, and I cannot for the life of me find a way to fix it.

Some ugly ways I was thinking of to fix it:
Title: Re: Dynamic Menus
Post by: K on May 24, 2006, 03:34 PM
So what's the problem?  Looks like everything should be set up ok.

This line here is adding the click event handler:

mnu_textures[i].Click += new EventHandler(mnutextures_Click);


so in your event...

private void mnutextures_Click(object sender, System.EventArgs e)
{
     MenuItem m = (MenuItem)sender;
     MessageBox.Show("You clicked: " + m.Text);
}
Title: Re: Dynamic Menus
Post by: shout on May 24, 2006, 03:44 PM
Quote from: K on May 24, 2006, 03:34 PM
So what's the problem? Looks like everything should be set up ok.

This line here is adding the click event handler:

mnu_textures[i].Click += new EventHandler(mnutextures_Click);


so in your event...

private void mnutextures_Click(object sender, System.EventArgs e)
{
MenuItem m = (MenuItem)sender;
MessageBox.Show("You clicked: " + m.Text);
}


OMG WHY AM I SO STUPID?

I forgot about the sender object...
Title: Re: Dynamic Menus
Post by: MyndFyre on May 24, 2006, 05:25 PM
As a note, one of the things I like to do to associate data with a menu item are to subclass it.  For instance:


public class FileMenuItem : MenuItem {
  private string m_path;
  public FileMenuItem(string path)
  {
    this.m_path = path;
    this.Text = Path.GetFileName(path);
  }

  public string FilePath { get { return m_path; } }
}

Just a thought.  ;-)