How to create a drop down menu in WinForms and C#

前端 未结 5 814
庸人自扰
庸人自扰 2020-12-16 15:40

I am new to using Visual Studio/WinForms/C#

I am trying to create a simple drop down menu where each item can have a value and a label.

This is what I would do

5条回答
  •  一整个雨季
    2020-12-16 16:03

    ComboBox displays the result returns from the ToString call, so you can define a Display class that wraps value and display text and add those to your combobox.

    That is:

     public class ItemDisplay
     {
         private readonly string m_displayText;
    
         public ItemDisplay(TValue value, String displayText)
        {
            this.Value = value;
            m_displayText = displayText;
        }
    
        public TValue Value { get; set; }
    
        public override string ToString()
        {
            return m_displayText;
        }
    }
    

    and add items to your combobox as follows:

     comboBox1.Items.Add(new ItemDisplay(1, "FirstValue"));
     comboBox1.Items.Add(new ItemDisplay(2, "Second"));
     comboBox1.Items.Add(new ItemDisplay(3, "Third"));
    

提交回复
热议问题