BindingSources 会为您解决这个问题。
例如说我有两个班级,教师和学生:
public class Teacher
{
private List<Student> _students = new List<Student>();
public string Name { get; set; }
public string Class { get; set; }
public List<Student> Students { get { return _students; } }
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
然后,您可以创建一个代表 Master/Detail 情况的 Teachers 列表:
List<Teacher> teachers = new List<Teacher>();
Teacher t = new Teacher();
t.Name = "Mr. Smith";
t.Class = "A1";
teachers.Add(t);
Student s = new Student();
s.Name = "Jimmy Jones";
s.Age = 6;
t.Students.Add(s);
s = new Student();
s.Name = "Jane Doe";
s.Age = 5;
t.Students.Add(s);
t = new Teacher();
t.Name = "Ms. Allen";
t.Class = "B3";
teachers.Add(t);
s = new Student();
s.Name = "Sally Student";
s.Age = 7;
t.Students.Add(s);
在我的表单上,我有两个DataGridViews
,teachersDataGridView
和studentsDataGridView
两个绑定源teachersBindingSource
和studentsBindingSource
.
我把所有东西都连接起来:
teachersBindingSource.DataSource = teachers;
studentsBindingSource.DataSource = teachersBindingSource;
studentsBindingSource.DataMember = "Students";
teachersDataGridView.DataSource = teachersBindingSource;
studentsDataGridView.DataSource = studentsBindingSource;
当在表格上运行时,从教师网格中选择一项更改学生网格,就好像施了魔法一样。
为了管理插入、更新和删除,您需要自己实现某种更改跟踪(或使用 ORM,例如 Entity Framework 或 nHibernate)。这是一个值得自己提出问题的主题,因此请阅读这些技术(并查看我喜欢的下面的博客文章),并在遇到一些具体问题时回来。
对于这个答案,我从这篇优秀的帖子中大量借鉴了——我给出的示例是完整的,并且避免了该作者示例中的许多复杂性,但最终您可能至少想知道他讨论的所有内容。下载他的演示并看看。