18

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 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.

2
  • Your title and description are confusing. This has nothing to do with menus. Commented Dec 31, 2014 at 16:41
  • Your best bet is to fill the items with the strings you want to display, then in code you just have conditions based off what the user selected.
    – Baddack
    Commented Dec 31, 2014 at 16:45

5 Answers 5

34

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.

6
  • 1
    Thank you for your help. After applying your code I am seeing 3 option with the following text option "POS.ComboItem" where POS is the namespace I should see "One", "two", "Three"
    – Jaylen
    Commented Dec 31, 2014 at 17:00
  • It works for me. Either override ToString or define the DisplayMember property. I wrote comboBox1.DisplayMember = "Text"; comboBox1.ValueMember = "ID";, but you can set these properties in the properties window as well. Commented Dec 31, 2014 at 17:05
  • How do I set the selected Item? So I read what need to be selected record from a database but I am unsure how to make ID = 10 to be selected. here is what I have tried var selectedVender = (ComboItem)InputVendors.SelectedValue; selectedVender.ID = i._vendorID; but this is not changing the selected item in the menu. the value of i._vendorID is being returned correctly but it is not setting the drop down menu correctly.
    – Jaylen
    Commented Jan 18, 2015 at 18:14
  • 1
    If you have set comboBox1.ValueMember = "ID" then you can simply write comboBox1.SelectedValue = 10; Commented Jan 18, 2015 at 19:49
  • 1
    OR if you have your items in a list or in an array that you assigned to the DataSource property of the combobox, you can lookup the index in this collection and write comboBox1.SelectedIndex = theIndex;. Commented Jan 18, 2015 at 20:00
8

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){}.

5

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;
1
  • 1
    Actually, I am reading values from the database where the value is the line item id and the text is the name item read from the database
    – Jaylen
    Commented Dec 31, 2014 at 17:02
0

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"));
-2

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;" })

`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.