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

前端 未结 5 813
庸人自扰
庸人自扰 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:02

    If you want a value and a caption (label), create an appropriate class

    class ComboItem
    {
        public int ID { get; set; }
        public string Text { get; set; }
    }
    

    In the ComboBox you then set the DisplayMember property to Text and the ValueMember property to ID.


    The DropDownStyle of the ComboBox determines its behavior. DropDownStyle.DropDown enables the user to type in text. With DropDownStyle.DropDownList the user can only select items from the list.


    You can fill the ComboBox like this:

    myCombo.DataSource = new ComboItem[] {
        new ComboItem{ ID = 1, Text = "One" },
        new ComboItem{ ID = 2, Text = "Two" },
        new ComboItem{ ID = 3, Text = "Three" }
    };
    

    The DataSource can be any kind of enumerable.

    You can retrieve the selected ID like this

    int id = (int)myComboBox.SelectedValue;
    

    Note that you can add any type of item to the ComboBox. If you don't specify the DisplayMember and ValueMember properties, the ComboBox uses the ToString method of the object to determine the text displayed and you can retrieve the selected item (not selected value) through the SelectedItem property.

    If you add objects of this type ...

    class Person
    {
        public int PersonID { get; set }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
     }
    

    ...to the ComboBox, you can retrieve the selected item like this

    Person selectedPerson = (Person)myComboBox.SelectedItem;
    int personID = selectedPerson.PersonID;
    

    The ComboBox will display the first and last names of the persons.

提交回复
热议问题