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

2020-03-01 10:18发布

问题:

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

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

This is what I would do in HTML if I was creating a web app. But how can I do this with C# and WinForms?

<select>
<option value="0">Please select One</option>
<option value="1">The first Options</option>
<option value="2">The Second Options</option>
<option value="3">The Third Options</option>
</select>

I tried ComboBox but it seems I am not allowed to add a value and a label and the user can still type anything they want.

I tried a ListBox but that did not allow me to use value and label as well.

回答1:

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.



回答2:

It seems like the value is just a reference to what item is selected, correct? Then you can use the index of the combobox, makes it a lot easier.

Not sure if your items are known before build, if yes, then just add them in the designer, properties of the combobox. If not, then you can add them dynamically by just doing:

        List<string> items = new List<string>() { "item1", "item2" };
        comboBox1.DataSource = items;

And to know what item is selected:

        int index = comboBox1.SelectedIndex;


回答3:

You need to set a datasource for your Combobox, it's better if you create a class and pass a list of Objects, for example:

private void Init()
{
    List<Item> items = new List<Item>();
    items.Add(new Item() { Text = "displayText1", Value = "ValueText1" });
    items.Add(new Item() { Text = "displayText2", Value = "ValueText2" });
    items.Add(new Item() { Text = "displayText3", Value = "ValueText3" });

    comboBox1.DataSource = items;
    comboBox1.DisplayMember = "Text";
    comboBox1.ValueMember = "Value";

}

public class Item
{
    public Item() { }

    public string Value { set; get; }
    public string Text { set; get; }
}

Put the Init() method in your FormName_Load(object sender, EventArgs e){}.



回答4:

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<TValue>
 {
     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<int>(1, "FirstValue"));
 comboBox1.Items.Add(new ItemDisplay<int>(2, "Second"));
 comboBox1.Items.Add(new ItemDisplay<int>(3, "Third"));


回答5:

For creating a dropdown in controller use the selectlistitem in get method. And same you need to paas in post method too.

            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem
            {
                Text = "car",
                Value = "car"
            });


            ViewBag.List = new SelectList(items, "Text", "Value");

In view you need to pass dropdownlist.

   @Html.DropDownList("option", (ViewBag.List as SelectList), "Select", new { @style ="padding:5.5px;margin-bottom:8px;margin-right:-5px;" })

`