Rashed bin hares
Rashed bin hares

Reputation: 21

cast string to ToolStripMenuItem in vb.net

I want to cast a string to ToolStripMenuItem using DirectCast function. My code is:

   Dim ParentMenu As ToolStripMenuItem = 
       DirectCast(ComboBox1.SelectedItem, ToolStripMenuItem)

but it raise the following error

Unable to cast object of type 'System.String' to type 'System.Windows.Forms.ToolStripMenuItem'.

Upvotes: 0

Views: 1322

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18310

You cannot cast a String to a ToolStripMenuItem because of the simple fact that a String is not a ToolStripMenuItem! The DirectCast function requires some kind of relationship (like inheritance) between the two objects to work. This means that one of the two objects must be the same type as the other, or that one of them must inherit or implement the other one.

Read more about DirectCast: https://msdn.microsoft.com/en-us/library/7k6y2h6x.aspx

If you want it to be done in one line do:

Dim ParentMenu As New ToolStripMenuItem(ComboBox1.SelectedItem.ToString())

You will also need to use .ToString() or CStr() since ComboBox1.SelectedItem is returned as an Object.

Upvotes: 4

Related Questions