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.
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:
Put the
Init()
method in yourFormName_Load(object sender, EventArgs e){}
.If you want a value and a caption (label), create an appropriate class
In the ComboBox you then set the
DisplayMember
property toText
and theValueMember
property toID
.The
DropDownStyle
of the ComboBox determines its behavior.DropDownStyle.DropDown
enables the user to type in text. WithDropDownStyle.DropDownList
the user can only select items from the list.You can fill the
ComboBox
like this:The
DataSource
can be any kind of enumerable.You can retrieve the selected ID like this
Note that you can add any type of item to the ComboBox. If you don't specify the
DisplayMember
andValueMember
properties, the ComboBox uses theToString
method of the object to determine the text displayed and you can retrieve the selected item (not selected value) through theSelectedItem
property.If you add objects of this type ...
...to the ComboBox, you can retrieve the selected item like this
The ComboBox will display the first and last names of the persons.
For creating a dropdown in controller use the selectlistitem in get method. And same you need to paas in post method too.
In view you need to pass dropdownlist.
`
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:
and add items to your combobox as follows:
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:
And to know what item is selected: