Search code examples
c#.netwinformscombobox

How can i change the Name that is Displayed in the Combobox?


I am building a Studentlist and don't know how to overcome a problem. I am using a Combobox to display all the Students that have been created. I save the Students directly into the Combobox using this code:

private void btnSpeichern_Click(object sender, EventArgs e)
        {
            Student StudentSave = new Student
            {
                ID = txtStudentID.Text,
                FirstName = txtFirstName.Text,
                LastName = txtLastName.Text,
                Age = nudAge.Value,
                Height = nudHeight.Value,
                Schoolclass = txtSchoolClass.Text,
                Gender = cbxGender.Text,
            };

            cbxStudentIDs.Items.Add(StudentSave);
        }

cbxStudentIDs stands for the Combobox. I would like to have the Student ID as the name that is displayed, but It shows "WindowsFormsApp2.Form1+Student" for every Student I save.

I'm using Visual Studio 2019 C#. Thanks for any helpful advice!


Solution

  • You could begin by declaring a property of BindingList<Student>. For example,

    BindingList<Student> StudentCollection = new BindingList<Student>();
    

    You could then bind this list to the ComboBox using the following.

    cbxStudentIDs.DataSource = StudentCollection;
    cbxStudentIDs.DisplayMember = "ID";
    

    The DisplayMember ensures that the ID property of Student is used as Display String for ComboBox.

    You could now continue adding the Student to the newly created Collection as

    Student StudentSave = new Student
                {
                    ID = txtStudentID.Text,
                    FirstName = txtFirstName.Text,
                    LastName = txtLastName.Text,
                    Age = nudAge.Value,
                    Height = nudHeight.Value,
                    Schoolclass = txtSchoolClass.Text,
                    Gender = cbxGender.Text,
                };
     StudentCollection.Add(StudentSave);
    
    

    BindingList<T> supports two-way databinding.This would ensure each time you add a new item to your collection (StudentCollection), the ComboBox would be refreshed accordingly.