views:

28

answers:

2

This may have been already asked but I can't seem to find this specific question, so here goes...

I have a form in C# where every textbox is bound to a field in a row. Rows can be cycled through by some buttons on the bottom but all the data displayed at a time in the from is from one row. Any changes that are made get updated back to the database when the user clicks "update"

One field (class) is an enumeration (0,1,2) where only the value is stored in the database, but doesn't mean much to the user. I was asked to make this more obvious to the user, so I decided to go with a dropdown style combo box. Since the database didn't have any reference to what the values meant, I decided to use the DataBindings instead of DataSource so I could just use the index as the data bind, but it seems that SelectedItem or Value are not the way to do this.

Here is my goal:
1 exists in database, so "B" is selected in combo box.
User selects "C" and updates the database, 2 is now stored in the database.

Any thoughts on what I need to get this working?

A: 

I assume you have a BindingSource on your form to bind to the data. You can bind the SelectedIndex property of the ComboBox as follows:

comboBox.DataBindings.Add("SelectedIndex", bindingSource, "PropertyInTheDataSource");
Thomas Levesque
But I.. he... I... ugh - You are right sir :) I should have known better than using the Design Editor to see my options
Fry
A: 

Actually I was able to bind it to a custom Object. It's a little too much work for such a simple task. But you have complete control on Display/Value pairs. Anyway, I thought I'd share and you decide:
Create a new class (say CustomItem) with 2 fields:

Public int Value{get;set;}  
public string Title {get;set;}  

Then in you form:

var item1 = new CustomItem() { Title = "A", Value = 10 };
        var item2 = new CustomItem() { Title = "B", Value = 20 };
        var item3 = new CustomItem() { Title = "C", Value = 30 };
        var lst = new List<CustomItem>();
        lst.Add(item1);
        lst.Add(item2);
        lst.Add(item3);
        comboBox1.DataSource = lst;
        comboBox1.DisplayMember = "Title";
        comboBox1.ValueMember = "Value";

Now You have a databound combobox in case you don't have BndingSource in your form.
Just remember to define your class's Title and Value as properties otherwise it wouldn't work.

Kamyar