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.