开发者

.Net ToolStripMenuItem - how to access click-event for items generated while form is being loaded (in runtime)

I have a form which upon its loading events retrieves data and populates some menu-items. I am adding menu-items using

Viewer.AudioTrackToolStripMenuItem.DropDownItems.Add(myValue)

The number of menu-items created are not always the same. Sometimes they are 2, other times they are 4 depending on the data being retrieved.

Since the menu-items are created during "run-time", how can I now intercept when a user click/select a menu-item (I mean I don't know the name of the control and its click-event). If the menu-items were known before-hand, I would simply create the menu-item in design-time and I would have my click-event but now I don't.

Any help would be appreciated. Thank you.

Edit: you got me on track but I still got some error-messages. Just to clarify, the code is as follows:

myValue = TextBetween(value1, "s|", "|e") 'myValue is the result of a function
                                          'where myValue is a string
myValue.click += New System.EventHandler(myValue_Click) 'ERROR
Me.AudioTrackToolStripMenuItem.DropDownItems.Add(myValue)

Now if I run the code I get the following errors:

1) 'click' is not a member of 'String'

2) Delegate 'System.EventHandler' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.

Could above errors be because my menu-i开发者_如何学Ctems are named in accordance with a result from a variable (myValue)?

edit2: I got everything working by using the following code:

Dim menuItem As ToolStripMenuItem
myValue = TextBetween(value1, "s|", "|e")
menuItem = New ToolStripMenuItem(myValue)
Me.AudioTrackToolStripMenuItem.DropDownItems.Add(MenuItem.ToString, Nothing, AddressOf ToolStripMenuItem_Click)

then I added the following sub:

Private Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim menuItem As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)
    If menuItem IsNot Nothing Then
          'item just clicked. 
          MessageBox.Show(menuItem.Text)
    End If
End Sub


Define myvalue_click method to handle all myValue clicks. Add event handles programmatically, like:

this.myValue.Click += new System.EventHandler(this.myValue_Click);  


You can add the event at runtime too, e.g..

Since your myValue is a string, you'll first need to create a button for it:

ToolStripItem toolStripItem = new ToolStripItem();

toolStripItem.Text = myValue;
toolStripItem.Click += new EventHandler(toolStripItem_Click);

Viewer.AudioTrackToolStripMenuItem.DropDownItems.Add(toolStripItem);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜