Convert string to ToolStripMenuItem

Posted by Rashedbin under VB.NET on 8/19/2015 | Points: 10 | Views : 5027 | Status : [Member] | Replies : 2
i want to cast a string to ToolStripMenuItem in vb.net 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'. please,answer me.




Responses

Posted by: Sheonarayan on: 8/19/2015 [Administrator] HonoraryPlatinum | Points: 25

Up
0
Down
The simple reason for this is that ToolStripMenuItem is not of string type so it is not getting converted. Probably you need to instantiate ToolStripMenuItem by passing the ComboBox1.SelectedItem or ComboBox1.SelectedItem.Value and then try to cast it.

Thanks


Regards,
Sheo Narayan
http://www.dotnetfunda.com

Rashedbin, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vedikaledange on: 1/8/2019 [Member] Starter | Points: 25

Up
0
Down
You may try this code:

private void BuildMenuItems()
{
ToolStripMenuItem[] items = new ToolStripMenuItem[2]; // You would obviously calculate this value at runtime.your splited string length goes here
for (int i = 0; i < items.Length; i++)
{
items[i] = new ToolStripMenuItem();
items[i].Name = "dynamicItem" + i.ToString(); //You have to set your string value here
items[i].Tag = "specialDataHere";
items[i].Text = "Visible Menu Text Here";
items[i].Click += new EventHandler(MenuItemClickHandler);
}

myMenu.DropDownItems.AddRange(items);
}

private void MenuItemClickHandler(object sender, EventArgs e)
{
ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
// Take some action based on the data in clickedItem
}

DOT NET

Rashedbin, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response