Search code examples
winformsc#-4.0datagridviewdatagridcomboboxcolumn

Why DataGridView ComboBox displays the ValueMember value?


I am currently working in C# window application. There I use data grid view combo box in the DataGridView. While clicking the drop down box it displays the Name field, if I select the name field from the drop box, it displays the value member value in DataGridView ComboBox.

Why I am not getting the display member value in the Combo box?

In databindindcomplete function I define the value for the ComboBox:

((DataGridViewComboBoxColumn)dgvItem_1.Columns["Student"]).DataSource = objDBContext.Stu_student;
((DataGridViewComboBoxColumn)dgvItem_1.Columns["Student"]).DisplayMember = "STUDENT_NAME";
((DataGridViewComboBoxColumn)dgvItem_1.Columns["Student"]).ValueMember = "STUDENT_ID";

If I select a value in the ComboBox following value displayed in drop down list

Name
-----
Raja
Ramesh
Rani

If I select Raja in the list the ComboBox displays the corresponding STUDENT_ID in the ComboBox. But I want to display the Student name in the ComboBox.

Can anyone tell me why I am getting the ValueMember value in the DataGridView ComboBox?


Solution

  • So in my simple example where I've got a Student class that looks like:

    public class Student
    {
        public string Name { get; private set; }
        public int StudentId{ get; private set; }
        public Student(string name, int studentId)
        {
            Name = name;
            StudentId= studentId;
        }
    
        private static readonly List<Student> students = new List<Student>
        {
            { new Student("Chuck", 1) },
            { new Student("Bob", 2) }
        };
    
        public static List<Student> GetStudents()
        {
            return students ;
        }
    }
    

    and I set up my binding for the combobox like this:

            DataGridViewComboBoxColumn comboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];
            comboBoxColumn .DataSource = Student.GetStudents();
            comboBoxColumn .DisplayMember = "Name";  
            comboBoxColumn .ValueMember = "StudentId";        
    

    I get my student names in the dropdown and when I select one, the selected name shows up in the cell.