i want to get each ToolStripMenuItem of my MDI form's value by looping through them and using reflection as following:
FieldInfo[] menuitems = GetType().GetFields(BindingFlags.GetField |
BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var ite开发者_如何学Pythonm in menuitems )
if (item.FieldType.Equals(typeof(ToolStripMenuItem)))
MessageBox.Show(
item.FieldType.GetProperty("Tag").GetValue(item, null).ToString());
but i got "Object does not match target type" error, i am confused and don't know what object to specify as the source object to get value of.
please guide me through... thank you in advance.
This is not a case for reflection.
To get the menuitems, you should first get a reference to your ToolStrip and from there iterate over its Controls
collection.
code would then look something like this:
foreach(Control ctrl in _myToolStrip.Controls)
{
MessageBox.Show(ctrl.Tag);
}
use something like GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString()
.
精彩评论