0

I am working on Access Control List in which I have to show/hide Menu Items based on assigned roles. I have referreed every menu Item via TAG. Now I have an array stored all TAG names.

Is it possible I just loop thru Array of Tag names and just refer Menu Item control by Tag or name without looping thru all menuStrip Items and compare current control and make it visible?

Thanks

Volatil3
  • 14,253
  • 38
  • 134
  • 263

2 Answers2

0

I don't understand exactly what you are trying to achieve, but maybe this code is a help to you:

    private void button1_Click(object sender, EventArgs e) {
        var menus = new string[] { "Every", "menu", "you", "want", "to", "show" };
        foreach (var mnu in this.GetType().GetFields(
            BindingFlags.Instance | 
            BindingFlags.NonPublic | 
            BindingFlags.GetField)) {
            var member = mnu.GetValue(this) as MenuStrip;
            if (null != member) {
                member.Visible = (menus.Contains(member.Tag.ToString()));
            }
        }
    }
Peter Stock
  • 301
  • 1
  • 7
  • Well, then adapt the above code to your needs. Btw, it uses System.Reflection and System.Linq. You can omit the `menus` variable and just compare to the specific Tag you want. – Peter Stock Apr 04 '13 at 07:33
  • *var member = mnu.GetValue(this) as MenuStrip;* It is always coming as NULL. Can't I just get *member.Tag*? I can see *Name* Property but not Tag – Volatil3 Apr 04 '13 at 07:45
0

I think I understand better now. The following code turns a ToolStripMenuItem visible (or change to whatever Type your object is). I use the Name, because for using the Tag, you would have to enumerate all objects.

    private void ShowItem(string menuItemName) {
        var field = this.GetType().GetField(
            menuItemName, 
            BindingFlags.Instance |
            BindingFlags.NonPublic |
            BindingFlags.GetField);
        var mnu = field.GetValue(this) as ToolStripMenuItem;
        if (null != mnu) {
            mnu.Visible = true;
        }
    }

Note that this must be the Form that contains the Menu.

Peter Stock
  • 301
  • 1
  • 7