[c#] How to set selected value from Combobox?

I use combobox in c# windows form. I bound the item list as below:

var employmentStatus = new BindingList<KeyValuePair<string, string>>();

employmentStatus.Add(new KeyValuePair<string, string>("0", "[Select Status]"));
employmentStatus.Add(new KeyValuePair<string, string>("1", "Contract"));
employmentStatus.Add(new KeyValuePair<string, string>("2", "Part Time"));
employmentStatus.Add(new KeyValuePair<string, string>("3", "Permanent"));
employmentStatus.Add(new KeyValuePair<string, string>("4", "Probation"));

employmentStatus.Add(new KeyValuePair<string, string>("5", "Other"));
cmbEmployeeStatus.DataSource = employmentStatus;
cmbEmployeeStatus.ValueMember = "Key";
cmbEmployeeStatus.DisplayMember = "Value";
cmbEmployeeStatus.SelectedIndex = 0;

I save the selected value in database eg.1 or 2. Now I want to set selected value from database item like:

cmbEmployeeStatus.SelectedValue =employee.employmentstatus;     

But combobox not selected with value. How can I do that?

This question is related to c# .net winforms data-binding combobox

The answer is


I suspect something is not right when you are saving to the db. Do i understand your steps as:

  1. populate and bind
  2. user selects and item, hit and save.. then you save in the db
  3. now if you select another item it won't select?

got more code, especially when saving? where in your code are initializing and populating the bindinglist


try this

combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"

Try this:

KeyValuePair<string, string> pair = (KeyValuePair<string,string>)this.ComboBox.SelectedItem;

In windows Appliation we use like this

 DDLChangeImpact.SelectedIndex = DDLChangeImpact.FindStringExact(ds.Tables[0].Rows[0]["tmchgimp"].ToString());
 DDLRequestType.SelectedIndex = DDLRequestType.FindStringExact(ds.Tables[0].Rows[0]["rmtype"].ToString());

cmbEmployeeStatus.Text = "text"

In order to do the database style ComboBoxes manually trying to setup a relationship between a number (internal) and some text (visible), I've found you have to:

  1. Store you items in a list (You are close - except the string,string - need int,string)
  2. DataSource property to the list (You are good)
  3. DataMember,DataValue (You are good)
  4. Load default value (You are good)
  5. Put in value from database (Your question)
  6. Get value to put back in database (Your next question)

First things first. Change your KeyValuePair to so it looks like:

(0,"Select") (1,"Option 1")

Now, when you run your sql "Select empstatus from employees where blah" and get back an integer, you need to set the combobox without wasting a bunch of time.

Simply: *** SelectedVALUE - not Item ****

cmbEmployeeStatus.SelectedValue = 3;   //or

cmbEmployeeStatus.SelectedValue = intResultFromQuery;   

This will work whether you have manually loaded the combobox with code values, as you did, or if you load the comboBox from a query.

If your foreign keys are integers, (which for what I do, they all are), life is easy. After the user makes the change to the comboBox, the value you will store in the database is SelectedValue. (Cast to int as needed.)

Here is my code to set the ComboBox to the value from the database:

if (t is DBInt) //Typical for ComboBox stuff
    {
    cb.SelectedValue = ((DBInt)t).value;
    }

And to retrieve:

((DBInt)t).value = (int) cb.SelectedValue;

DBInt is a wrapper for an Integer, but this is part of my ORM that gives me manual control over databinding, and reduces code errors.

Why did I answer this so late? I was struggling with this also, as there seems to be no good info on the web about how to do this. I figured it out, and thought I'd be nice and post it for someone else to see.


To set value in the ComboBox

cmbEmployeeStatus.Text="Something";

Try this one.

cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);

Hope that helps. :)


Below will work in your case.

cmbEmployeeStatus.SelectedItem =employee.employmentstatus;

When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index. If the object does not exist in the list, the SelectedIndex property is left at its current value.

EDIT

I think setting the Selected Item as below is incorrect in your case.

cmbEmployeeStatus.SelectedItem =**employee.employmentstatus**;

Like below

var toBeSet = new KeyValuePair<string, string>("1", "Contract");
cmbEmployeeStatus.SelectedItem = toBeSet;

You should assign the correct name value pair.


Use the SelectedIndex property for the respective employee status in the combo box.


A possible solution:

cmbEmployeeStatus.SelectedValue = cmbEmployeeStatus.Items.FindByText("text").Value;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to data-binding

Angular 2 Checkbox Two Way Data Binding Get user input from textarea Launch an event when checking a checkbox in Angular2 Angular 2 two way binding using ngModel is not working Binding ComboBox SelectedItem using MVVM Implement Validation for WPF TextBoxes Use StringFormat to add a string to a WPF XAML binding how to bind datatable to datagridview in c# How to format number of decimal places in wpf using style/template? AngularJS - Binding radio buttons to models with boolean values

Examples related to combobox

How to set combobox default value? PHP code to get selected text of a combo box How to add items to a combobox in a form in excel VBA? How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null) Get Selected value of a Combobox jQuery "on create" event for dynamically-created elements How to get the selected item of a combo box to a string variable in c# HTML combo box with option to type an entry twitter bootstrap autocomplete dropdown / combobox with Knockoutjs C# winforms combobox dynamic autocomplete