Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows.Form ComboBox Cannot set the SelectedValue Property of Unbound Control

Tags:

c#

combobox

I cannot set the default combobox selected value for an unbound combobox. Here is my code:

         System.Console.WriteLine("Current Tag Org Id = " + CurrentTag.Org.OrgId);
         ddlRUC.SelectedValue = CurrentTag.Org.OrgId;
         System.Console.WriteLine("ddlRUC selected value = " + ddlRUC.SelectedValue);

Here is the output: Current Tag Org Id = 285 ddlRUC selected value =

Note that ddlRUC.SelectedValue has not been set to 285. Does the datasource need to be bound in order to use the SelectedValue property? If so, how do I set the default item shown in a combobox that is not bound?

like image 689
Amar Premsaran Patel Avatar asked Nov 27 '22 15:11

Amar Premsaran Patel


2 Answers

A combobox (like a Listbox) has 2 mechanisms for dealing with the selection. Either:

  1. You assign a List to the DataSource property and set the ValueMember and DisplayMember to the names of properties of items of that list. Or,

  2. You fill the Items property with objects of your choice, the ToString() will be displayed.

In scenario 1) you can use SelectedValue to get/set the selection based on the ValueMember.

in scenario 2) you use SelectedItem property instead of SelectedValue

So the question is, how do you fill the Items?

like image 81
Henk Holterman Avatar answered Dec 18 '22 23:12

Henk Holterman


The SelectedValue property will only work for a databound listbox. If you can create your list items in a List<>, you can then bind the list to the control and SelectedValue will work as you would like.

like image 23
Scott Ewers Avatar answered Dec 18 '22 22:12

Scott Ewers