Domanda

Can someone please explain to me why the hell? When I try to set a MenuStrip Item calling it by name it gives me an exception?

An unhandled exception of type 'System.NullReferenceException' occurred in Sample.exe

Additional information: Object reference not set to an instance of an object.

Either of the following statements cause errors.

frmMenu.MenuStripfrmMenu.Items(key:="Enter").Enabled = False

frmMenu.MenuStripfrmMenu.Items("Enter").Enabled = False

However when I call Items using an integer it works perfectly.

È stato utile?

Soluzione

You have to use the name property of the menu item, not the text property:

Public Sub New()
  InitializeComponent()

  Dim menu As New MenuStrip
  Dim menuOne As New ToolStripMenuItem("Menu One") With {.Name = "menuOne"}
  Dim menuTwo As New ToolStripMenuItem("Menu Two") With {.Name = "menuTwo"}
  menu.Items.Add(menuOne)
  menu.Items.Add(menuTwo)
  Me.Controls.Add(menu)

  menu.Items("menuOne").Enabled = False
  AddHandler menu.Items("menuTwo").Click, AddressOf Menu_Click
End Sub

Private Sub Menu_Click(ByVal sender As Object, ByVal e As EventArgs)
  MessageBox.Show("This menu works.")
End Sub
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top