【问题标题】:ListBox only updates the first time its called? c#ListBox 仅在第一次调用时更新? C#
【发布时间】:2017-06-08 12:00:28
【问题描述】:

我在Form1 中有一个ListBox studentListBox,它显示由Form2 填充的studentList 的成员。有一个类Student,其中包含关于每个学生的一些不同属性。

我在Form1 中还有一个函数BindData(),它将studentListBox 数据源设置为studentList。它还将studentListBox 显示成员设置为Name,这是Student 类中的一个属性。

Form1

public void BindData()
        {
            if (studentListHome != null)
            {
                studentListBox.DataSource = studentListHome;
                foreach(Student s in studentListHome)
                {
                    studentListBox.DisplayMember = "Name";
                }

            }
        }

BindData 在Form1_Load 上调用,也可以通过点击刷新按钮调用。

Form2 创建每个学生并将其添加到Form1 内部的studentList 它在单击提交按钮时执行此操作

Form2

private void submitButton_Click(object sender, EventArgs e)
        {
            if (comparator(nameInput) &
               comparator(idInput) &
               comparator(bdayInput)){
                variable_assignment();
                var tempStudent = StudentCreation();
                if(tempStudent != null)
                {
                    studentListForm2.Add(tempStudent);
                }
                testList.Add(tim);
                testList.Add(john);
                testList.Add(tempStudent);

                foreach(Student s in testList)
                {
                    homeForm.StudentListHome.Add(s);
                }
                homeForm.BindData();
            }
        }

comparator() 是一个确保用户输入字段不为空的函数。 variable_assignment() 将用户输入分配给相关变量。 StudentCreation() 是一个将Student 实例化的函数

就像我在标题中提到的那样,ListBox 仅在第一次调用时更新,之后,它保持完全相同。我知道Students 被添加到ListBox 绑定到的List<Student> 中,因为我是Console.WriteLineing 他们,我可以看到每次提交时新的Student 被添加到studentList按钮被点击。

我该如何解决这个问题?

【问题讨论】:

  • 为什么要循环这个studentListBox.DisplayMember = "Name";?一次就够了。
  • 请参阅下面的答案,但如果您只想继续您的编码方式,请执行以下操作: if (studentListHome != null) { studentListBox.DataSource = null; studentListBox.DataSource = studentListHome; studentListBox.DisplayMember = "姓名"; }

标签: c# winforms listbox


【解决方案1】:

一些小事

if (studentListHome != null)
        {
            studentListBox.DataSource = studentListHome;
            foreach(Student s in studentListHome)
            {
                studentListBox.DisplayMember = "Name";
            }

        }

foreach 是多余的,因为您只需为列表框设置一次,而不是列表框中的每个项目。

    if (studentListHome != null)
    {
        studentListBox.DataSource = studentListHome;
        studentListBox.DisplayMember = "Name";
    }

接下来要回答您的问题,您必须使用 BindingList 而不是任何其他类型的集合,然后对于比较和排序,您可以在 Student 类本身上实现 IComparable 和 INotifiyPropertyChanged。

然后您不必再次重新绑定,只需修改 BindingList 实例来操作列表,列表框的行为就会与列表同步。

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多