ComboBox Databinding Problem with Text Property

R

Ryan Gregg

Sorry for the cross posting, but I wasn't sure the best group to answer
this question.

I've been running my head into this bug for a while now, and I'm hoping
that someone out there has a good fix for it. It's a fairly simple bug
that really should have been caught previously, although I haven't
checked to see if it actually existed in previous framework revisions.

Here's the gist of the problem:

Create an event handler for the form's Load event and add the following
code:
1. Set a ComboBox on the Form to use DisplayMember and ValueMember
properties for your data source.
2. Bind the ComboBox to some data source that has those members.
3. Set the ComboBox's Text property to a value not found in your data
source during the Load event
4. Now, put two buttons on the form, one to retrieve the value of the
Text property and another to retrieve the value of the SelectedItem
property. I used message boxes to show the values.
5. Compile and run this tiny app, and click the Text button first,
you'll notice that instead of getting the actual text displayed in the
combo box, you get the display text for the first item in the data
source. Likewise you'll get the first item from the SelectedItem
property, not a null value.

If the user clicks the drop down box or retypes the value into the combo
box, the Text and SelectedItem properties will be updated with the
correct (displayed) value.

Boy is this annoying! There has to be some what to fix this without
waiting for a new service pack or rewriting the combo box control! Any
ideas for a fix?

You can download my sample solution that illustrates this problem from
here: http://ryangregg.com/files/ComboBoxTest.zip

Hopefully someone out there has a good answer! Thanks in advance.

Ryan Gregg
 
S

Sijin Joseph

Try this change

private void Form1_Load(object sender, System.EventArgs e)
{

TestValuePair[] values = new TestValuePair[] {
new TestValuePair("Alpha", 1),
new TestValuePair("Beta", 10),
new TestValuePair("Gamma", 100)};

comboBox1.DisplayMember = "Display";
comboBox1.ValueMember = "Value";
comboBox1.DataSource = values;

comboBox1.SelectedIndex = -1;
comboBox1.Text = "Delta";
}




Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph
 
R

Ryan Gregg

Thanks for the suggestion Sijin. That seems to fix the problem, however
it's a pain that I have to take that action, seems it should be automatic.

At least it's a relatively easy fix to implement.

Thanks again.

Ryan Gregg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top