Binding class with master/detail into two datagridview

半城伤御伤魂 提交于 2019-12-05 17:40:34

BindingSources take care of this for you.

For example say I have two classes, Teachers and Students:

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; }
}

You can then create a list of Teachers which represents the Master/Detail situation:

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);

On my form I have two DataGridViews, teachersDataGridView and studentsDataGridView and two binding sources teachersBindingSource and studentsBindingSource.

I wire everything up like so:

    teachersBindingSource.DataSource = teachers;

    studentsBindingSource.DataSource = teachersBindingSource;
    studentsBindingSource.DataMember = "Students";

    teachersDataGridView.DataSource = teachersBindingSource;
    studentsDataGridView.DataSource = studentsBindingSource;

And as if by magic when running up on the form selecting an item from the teachers grid changes students grid.


For managing inserts, updates and deletes you will need to implement some sort of change tracking yourself (or use an ORM such as Entity Framework or nHibernate). It is a topic that deserves its own question so read up on those technologies (and look at the blog post I like below) and come back when you have some specific problems.


For this answer I borrowed heavily from this excellent post - the example I've given is complete and avoids a lot of the complexity in that authors example's, but eventually you will probably want to at least know about everything he discusses. Download his demos and have a look.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!