I assume that you were referring to a DataGridView that is for Windows Forms and a GridView for ASP.NET, although you have noted your question as such.
How do you bind data to a DataGridViewComboBoxColumn? You will need to set the DisplayMember and the ValueMember properties in the DataGridViewComboBoxColumn when setting up your DataSource. The MSDN link to DisplayMember shows an example, but it doesnβt quite show what you are requesting, as it sets both properties to the same thing.
DisplayMember is the text you want to see, and ValueMember will be the hidden base value associated with it.
For example, suppose you have a Choice class in your project that represents your choice 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 options. Ideally, you will have such a method at the service level, or you can create your own list elsewhere if you want (in your form code). For simplicity, I have combined all this in one class.
In your form, you bind the list to a 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
Now you should see "One" and "Two" in the combo box. When you get the selected value from it, it should be a base value of 1 or 2.
This is the idea of ββusing DisplayMember / ValueMember. This should get you going and help you adapt the data source that you used.
Ahmad mageed
source share