如何更改组合框中显示的名称?

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

我正在构建学生列表,但不知道如何解决问题。我正在使用组合框来显示所有已创建的学生。我使用以下代码将学生直接保存到组合框中:

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 代表组合框。我希望将学生 ID 作为显示的名称,但它为我保存的每个学生显示 "WindowsFormsApp2.Form1+Student"。

我正在使用 Visual Studio 2019 C#。感谢您提供任何有用的建议!

您不想将整个对象添加到组合框中,只是添加一个 ID 列表。所以你会改变 cbxStudentIDs.Items.Add(StudentSave);cbxStudentIDs.Items.Add(StudentSave.ID);

然后您必须将学生对象的实际状态保存在其他地方,您可以使用 ID link 到它,无论是数据库还是内存集合都由您决定。

或者,您可以 link 包含学生数据的数据源作为组合框的来源,并设置 DisplayMember 详细 here

您可以首先声明 BindingList<Student> 的 属性。例如,

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

然后您可以使用以下方法将此列表绑定到 ComboBox。

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

DisplayMember 确保 Student 的 ID 属性 用作 ComboBox 的显示字符串。

您现在可以继续将 Student 添加到新创建的 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> 支持 two-way databinding.This 将确保每次向 collection (StudentCollection) 添加新项目时,组合框都会刷新因此。