views:

589

answers:

1

I thought this was simple like in Access.

User needs to set the value of one column in a datatable to either 1 or 2.

I wanted to present a combobox showing "ONE", "TWO" and setting 1 or 2 behind the scene, like I did lots of times in Access-Forms.

On the other side, if the table is shown it shall not show 1 or 2 but the corresponding string in the ComboBox.

How can I get this simple task to work??

A: 

I assume you meant DataGridView, which is for Windows Forms, while the GridView is for ASP.NET although you tagged your question as such.

How are you binding the data to the DataGridViewComboBoxColumn? You'll need to set the DisplayMember and ValueMember properties on the DataGridViewComboBoxColumn while setting its DataSource. The MSDN link to DisplayMember shows an example, but it doesn't quite show what you're requesting since it sets both properties to the same thing.

The DisplayMember would be the text you want the user to see, and the ValueMember would be the hidden underlying value associated with it.

For the sake of an example, let's say you have a Choice class in your project that represents your selections and looks like this:

public class Choice
{
    public string Name { get; private set; }
    public int Value { get; private set; }
    public Choice(string name, int value)
    {
        Name = name;
        Value = value;
    }

    private static readonly List<Choice> possibleChoices = new List<Choice>
    {
        { new Choice("One", 1) },
        { new Choice("Two", 2) }
    };

    public static List<Choice> GetChoices()
    {
        return possibleChoices;
    }
}

GetChoices() will return a list containing your choices. Ideally you would have such a method in a service layer, or you could build your own list elsewhere if you wanted to (in your form's code behind). For simplicity I've lumped it all together in the same class.

In your form you would bind the list to the DataGridViewComboBoxColumn as follows:

// reference the combobox column
DataGridViewComboBoxColumn cboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];
cboBoxColumn.DataSource = Choice.GetChoices();
cboBoxColumn.DisplayMember = "Name";  // the Name property in Choice class
cboBoxColumn.ValueMember = "Value";  // ditto for the Value property

You should now see "One" and "Two" in the combobox. When you get the selected value from it, it should be the underlying 1 or 2 value.

That's the idea behind using DisplayMember/ValueMember. This should get you going and help you adapt the datasource you were using.

Ahmad Mageed
This is the perfect answer!Thank you Ahmad!Reinhard
Reinhard
How can we read the selected value of a dropdown cell in datagrid?
Maysam