【发布时间】: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 = "姓名"; }