DataGridView – 父级到子级数据库关系 – 更新子级DataGridView数据

有人会帮助我以下吗? 我有两个DataGridView对象,每个对象都显示一个DataTable,其中两个数据表与以下代码相关:

DataSet dSet = new DataSet(); DataTable ParentList = ListToDataTable(_listOfAllAlbumObjects); DataTable ChildList = ListToDataTable(_listOfAllTrackObjects); dSet.Tables.AddRange(new DataTable[]{ParentList, ChildList}); DataColumn parentRelationColumn = ParentList.Columns["AlbumId"]; DataColumn childRelationColumn = ChildList.Columns["AlbumId"]; dSet.Relations.Add("ParentToChild", parentRelationColumn, childRelationColumn); ParentDataGridView.DataSource = dSet; ParentDataGridView.DataMember = "ParentList"; ChildDataGridView.DataSource = ???; ChildDataGridView.DataMember = "ParentToChild"; 

两个DataTable实际上是List 转换为DataTables,具有以下内容:`

  public static DataTable ListToDataTable( IList data) { var props = TypeDescriptor.GetProperties(typeof(T)); var table = new DataTable(); for (var i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } var values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; } 

最初看起来每个DataGridView都适当地显示数据; 但是,子DataGridView不会更新父DataGridView中的任何记录更改。

我看到表需要通过绑定源互连; 但是我不相信这里有一个真正的绑定源。

有人可以引导我朝正确的方向前进吗? 谢谢。

有一篇MSDN文章显示了你想要做的事情:

如何:使用两个Windows窗体DataGridView控件创建主/详细信息表单

以下是这对您有用的方法:

通过设计器或通过代码向项目中添加两个BindingSource:parentBindingSource和childBindingSource。 然后试试这个代替你的代码。

 // Associate your BSs with your DGVs. ParentDataGridView.DataSource = parentBindingSource; ChildDataGridView.DataSource = childBindingSource; // (Most of) your code here: DataSet dSet = new DataSet(); DataTable ParentList = ListToDataTable(_listOfAllAlbumObjects); DataTable ChildList = ListToDataTable(_listOfAllTrackObjects); dSet.Tables.AddRange(new DataTable[]{ParentList, ChildList}); DataColumn parentRelationColumn = ParentList.Columns["AlbumId"]; DataColumn childRelationColumn = ChildList.Columns["AlbumId"]; dSet.Relations.Add("ParentToChild", parentRelationColumn, childRelationColumn); // Let's name this DT to make clear what we're referencing later on. ParentList.TableName = "ParentListDT"; // Rather than set the data properties on your DGVs, set them in your BindingSources. parentBindingSource.DataSource = dSet; parentBindingSource.DataMember = "ParentListDT"; childBindingSource.DataSource = parentBindingSource; childBindingSource.DataMember = "ParentToChild";