0

How can I write code for a toolstripmenu dropdownitem where the items are generates on FormLoad taking values from a database table?

How can I write an OnClick method for this items that don't exist before I run the program?

  • 1
    That's pretty unclear. You can certainly create toolstrip items from a dbase table but that doesn't accomplish much. The real meat is the *code* that executes when the user clicks the item. Where is that code? – Hans Passant May 05 '12 at 15:30
  • what exactly do you want to do with the event? is it enough to have the name of the item clicked?(in this case you could pass/read the name in the clicked event) or do you want to create classes/functions that are called if their name is the same as the item? (in this case you need something called 'late binding') – weberik Jan 10 '13 at 10:24

1 Answers1

0

Controls are just like any other objects. We are simply used to using a wysiwyg designer for specifying user interfaces.

So something like this:

void AddMenuItems(ToolStripItemCollection itemCollection, DataView view)
{
    foreach (DataRowView rowView in view)
        itemCollection.Add(MakeMenuItem(rowView.Row));
}

ToolStripItem MakeMenuItem(DataRow row)
{
    var item = new ToolStripMenuItem((string)row["Name"]);
    item.Tag = row;
    item.Click += new EventHandler(MenuItem_Click);
    return item;
}

void MenuItem_Click(object sender, EventArgs e)
{
    var row = ((ToolStripItem)sender).Tag as DataRow;
    MessageBox.Show((string)row["HelpText"]);
}

You may want to use something other than DataRow for the item data (e.g. an entity of some kind), and perhaps completely different logic to create items, but this illustrates the pattern: Create items just like you'd create any other object, add them to some menu already rooted in the form (you could create the root dynamically as well, but it's difficult to see what benefit could come of this), tag the items with their data, and obtain the data from the tag in the click handler.

This assumes you have fetched a table of datarows with two string-type columns, Name and HelpText. The name is used as the tool strip item label, and the help text is shown when clicking the item.

You could use this to create a menu representing the rows where name starts with an A doing something like this:

var view = GetMenuDataSet().Tables[0].DefaultView;
view.RowFilter = "Name LIKE 'A%'";
menu.Items.Clear();
AddMenuItems(menu.Items, view);

This assumes that GetMenuDataSet returns a DataSet containing a table with the two columns mentioned before, and that you've placed some root menu (e.g. a ContextMenuStrip) named "menu" on the form at design-time (or otherwise made sure it's created at the time this code runs).

To build a hierarchial structure you can invoke AddMenuItems and pass it some item's DropDownItems collection instead of the root menu's "Items" - both are of type ToolStripItemCollection.

The Dag
  • 1,811
  • 16
  • 22