Context Menus.

J

Jonathan Miller

I am dynamically generating some of the menuitems in a context menu. So far everything has worked well. I can add the menu items, I can even add a click event handler. However, this presents a new problem. Since all of the items are generated on the fly, they all point to the same handler code. How do I tell what menuitem was clicked on? I understand I can use the sender object to read the name, but I really need a way to associate a database primary key with each menu item. Any ideas on this?
 
J

Javier Campos

Jonathan Miller said:
I am dynamically generating some of the menuitems in a context menu. So
far everything has worked well. I can add the menu items, I can even add a
click event handler. However, this presents a new problem. Since all of
the items are generated on the fly, they all point to the same handler code.
How do I tell what menuitem was clicked on? I understand I can use the
sender object to read the name, but I really need a way to associate a
database primary key with each menu item. Any ideas on this?
I'd use the 'tag' property... it's an 'object' so you can associate anything
to it... like

MenuItem myItem = new MenuItem();
myItem.Text = "Blablabla";
myItem.Tag = "MyKey";

---

protected void onMenuItemClick(object sender, EventArgs e) {
string mySQL = "SELECT " + (string)((MenuItem)sender).Tag) + " FROM
myTable";
}

Hope this helps

Javier Campos
 
J

Javier Campos

Jonathan Miller said:
I agree the tag is where I would like to store my primary key. However,
it appears that a menuitem does not have tab property.
You're right. Well, as long as you're doing your MenuItems in runtime (not
in design mode), that'd be as easy as adding:

public class CustomMenuItem : System.Windows.Forms.MenuItem
{
private object _tag;
public object Tag { get { return _tag; } set { _tag = value; } }
}

And use CustomMenuItem instead of MenuItem :)
God bless non-sealed classes =)

Hope this helps,

Javier Campos

PS: it'd also be easy to make in design time, but you'd need an
"initializecomponent" and a Container so the IDE doesn't get crazy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top