DataBound ComboBox Problem

3 Feb

Problem:
When you want to use a data bound ComboBox in .NET (C#, VB, etc), you should set a few properties such as DataSource, DisplayMember and ValueMember.
It works fine unless you want to set SelectedValue for the first time. It won’t be set!

Solution:
I found that BindingContext property must be created before initializing SelectedValue:

ComboBox1.BindingContext = new BindingContext();
ComboBox1.DataSource = MyDataSet.DefaultView
ComboBox1.DisplayMember = "Title";
ComboBox1.ValueMember = "Code";
ComboBox1.SelectedValue = 1;
Advertisements

3 Responses to “DataBound ComboBox Problem”

  1. Mohammad February 3, 2009 at 7:31 am #

    Good starting my friend! Good luck with your writing 🙂

    • SkilledDeveloper February 3, 2009 at 7:33 am #

      Thank you Mohammad.

  2. Ronen June 30, 2012 at 1:09 pm #

    you can use SelectedItem insead of SelectedValue and it will work fine without the BindingContext

Leave a Reply to Mohammad Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: