none
C# How to retrieve custom property value from derived class ToolStripMenuItem RRS feed

  • Question

  • For 3 days now I've been searching the answer to this seemingly easy question. 

    I've created a class like so:

    public class SourceMenuItem : ToolStripMenuItem

    {

    private string connection;

    public string Conn
                {
                    get
                    {
                        return connection;
                    }

                    set
                    {
                        connection = value;
                    }
                }

    }

    My ToolStripMenuItem control is called SourceLeft System.Windows.Forms.ToolStripMenuItem

    Here's how I dynamically add items

    SourceMenuItem item = new SourceMenuItem();

    item.Text = "drive c:";

    item.Tag = "drive"; 

    item.Conn = "my string to retrieve";

    // (other stuff like ToolTipText, etc...)

    SourceLeft.DropDownItems.Add(item);

    And here's how I retrieve the values

    string text = "";

    string tag = "";

    string conn = "";

    int max = SourceLeft.DropDownItems.Count;                    

     

    for (i = 0; i < max; ++i)
                    {
                        text = SourceLeft.DropDownItems[i].Text;
                        tag = SourceLeft.DropDownItems[i].Tag.ToString(); // I have no problem retrieving those stored values.

                        // Here's where the problem starts
                        conn = SourceLeft.DropDownItems[i].Conn;
                    }

    The error message for .Conn is to be expected:

    ToolStripItem does not contain a definition for 'Conn' and no accessible extension method 'Conn' accepting a first argument of type 'ToolStripItem' could be found.

    I'm new to C# and couldn't find the answer about the code I'm missing to make this work: 

    I wish to address the .Conn property the same way I do with .Text & .Tag 

    Thank you for all your help

    Have a nice day.


    Wednesday, March 13, 2019 3:51 AM

All replies

  • Try this:

       conn = (SourceLeft.DropDownItems[i] as SourceMenuItem)?.Conn;

    If this menu item is different, then conn will be null.

    You can also assign multiple custom data (a class) to Tag property of ToolStripMenuItem. Then you do not have to create derived items. Just cast the Tag object.

    Wednesday, March 13, 2019 7:43 AM
  • That works perfectly well.

    I'll also look into assigning a class to the Tag property of ToolStripMenuItem

    Once again, thanks!

    Wednesday, March 13, 2019 11:27 AM