CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2001
    Location
    Minneapolis, MN, USA
    Posts
    150

    Adding MenuItems & Events at Runtime

    Does anyone know how to add MenuItems at runtime? Well...the below code does add them at runtime, but how do I add events to each added MenuItem? Basically I want to be able to change the Checked property to true and false and set the "checked" variable.

    DIM checked as Integer
    IF SubItem1 is Clicked THEN
    SubItem1.Checked = True
    SubItem2.Checked = False
    SubItem3.Checked = False
    checked = 1
    ELSEIF SubItem2 is Clicked THEN
    SubItem1.Checked = False
    SubItem2.Checked = True
    SubItem3.Checked = False
    checked = 2
    ELSEIF SubItem3 is Clicked THEN
    SubItem1.Checked = False
    SubItem2.Checked = False
    SubItem3.Checked = True
    checked = 3
    END IF

    CODE:
    Dim mnuSubItem As New MenuItem()
    mnuSubItem.Text = myGroup.GroupName

    If table.Rows(i).Item(1) = True Then
    USER_DEFAULTGROUP = table.Rows(i).Item(0)
    mnuSubItem.Checked = True
    Else
    mnuSubItem.Checked = False
    End If

    frmMAIN.mnuOffice.MenuItems.Add(mnuSubItem)

  2. #2
    Join Date
    Jun 2001
    Location
    MO, USA
    Posts
    2,868
    Take a look at "AddHandler" in the help.

  3. #3
    Join Date
    May 2000
    Location
    New York, NY, USA
    Posts
    2,878
    You need to add handler to the new item. Something like this

    Code:
    Option Strict On
    Public Class Form1
        Inherits System.Windows.Forms.Form
    
    #Region " Windows Form Designer generated code "
    #End Region
    
        Private Sub bttnMenuAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnMenuAdd.Click
            MyMenu.MenuItems.Add("MyMenu" & MyMenu.MenuItems.Count.ToString, _
                      New EventHandler(AddressOf Me.OptionClick))
        End Sub
    
        Private Sub bttnMenuRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnMenuRemove.Click
            If MyMenu.MenuItems.Count > 0 Then
                Dim mItem As MenuItem
                mItem = MyMenu.MenuItems(MyMenu.MenuItems.Count - 1)
                MyMenu.MenuItems.Remove(mItem)
            End If
        End Sub
    
        Private Sub OptionClick(ByVal sender As Object, ByVal e As EventArgs)
            Dim itemClicked As New MenuItem()
            itemClicked = CType(sender, MenuItem)
            MsgBox("You have selected the item " & itemClicked.Text)
        End Sub
    
    End Class
    Iouri Boutchkine
    [email protected]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured