Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net ComboBox Binding Issue

I have 2 comboboxes, each are bound to the the same DataTable like so:

    channelTypeCB.DataSource = SynergyData.ds.Tables["ChannelTypes"];
    channelTypeCB.DisplayMember = "channelType";
    channelTypeCB.ValueMember = "channelTypeID";
    channelTypeCB.BindingContext = new BindingContext();

    newSKChanTypeCB.DataSource = SynergyData.ds.Tables["ChannelTypes"];
    newSKChanTypeCB.DisplayMember = "channelType";
    newSKChanTypeCB.ValueMember = "channelTypeID";
    newSKChanTypeCB.BindingContext = new BindingContext();

When I click a button to insert a record into the database, I use channelType.SelectedValue... which is returning the incorrect value. I have a feeling it has something to do with using the ComboBox sort (which I set in the properties of the control in the design view). Has anyone ran into this problem?

This is programmed for a winforms application using C#

Edit:

For example, my Datatable stores values like:

channelType    channelTypeID
Web             2
Mailer          3
Catalog         4

This is sorted in the combobox, and when I select the first item (which would be "Catalog" when sorted) the SelectedValue returns 2, when I select the second item it returns 3.... I would have expected "Catalog" to return 4

like image 297
Chris Klepeis Avatar asked Dec 02 '25 19:12

Chris Klepeis


2 Answers

MSDN ComboBox.Sorted

Probably related to this

Attempting to set the Sorted property on a data-bound control raises an ArgumentException. You must sort the data using the underlying data model.

(Wasn't getting any errors though)

So instead of using the ComboBox.sort, I'm sorting the DefaultView of the DataTable:

SynergyData.ds.Tables["ChannelTypes"].DefaultView.Sort = "channelType";

Not convinced this is the the best way to go about it, but it works, and now selectedValue returns the correct thing

like image 184
Chris Klepeis Avatar answered Dec 04 '25 09:12

Chris Klepeis


You may be referring to channelTypeCB.SelectedValue in your code, when you need to be referring to newSKChanTypeCB.SelectedValue (this is a total guess based purely on your control names).

like image 29
MusiGenesis Avatar answered Dec 04 '25 09:12

MusiGenesis