【问题标题】:How can i change the Name that is Displayed in the Combobox?如何更改组合框中显示的名称?
【发布时间】:2020-02-27 15:58:33
【问题描述】:

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

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#。感谢您提供任何有用的建议!

【问题讨论】:

标签: c# .net winforms combobox


【解决方案1】:

您可以从声明BindingList<Student> 的属性开始。例如,

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

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

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

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

您现在可以继续将学生添加到新创建的集合中

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&lt;T&gt; 支持双向数据绑定。这将确保每次将新项目添加到集合 (StudentCollection) 时,组合框都会相应地刷新。

【讨论】:

  • 谢谢!这真的很有帮助:) 明天早上我会先测试它,然后告诉你它是怎么回事!另外,您知道是否有办法在没有数据库的情况下保存新学生?我不知道如何使用它,并希望使其尽可能简单。再次感谢?
  • 嘿嘿,现在这个名字已经完美显示了。但是,每次我输入一个 ID 时,以前的 ID 都会被删除。有什么办法可以保留它们吗?
  • @DennisScheurer 相信您正在添加到现有集合而不是重新分配集合?
【解决方案2】:

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

然后,您必须将学生对象的实际状态保留在可以使用 ID 链接到它的其他位置,无论是数据库还是内存中的集合都取决于您。

或者,您可以将数据源与学生数据链接为组合框的源,并将DisplayMember 设置为详细here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多