Vb.net 在一个datagridview中显示父datatable,在另一个datagridview中显示子datatable元素?
嗨,我已经创建了一个数据集和两个数据表。URLData表通过关键字列成为KeywordData表的父级Vb.net 在一个datagridview中显示父datatable,在另一个datagridview中显示子datatable元素?,vb.net,datagridview,datatable,dataset,Vb.net,Datagridview,Datatable,Dataset,嗨,我已经创建了一个数据集和两个数据表。URLData表通过关键字列成为KeywordData表的父级 'Create the primary object to hold both data tables Dim AllKeyWordInfo As DataSet = New DataSet("AllKeywordInfo") 'Create a Datatable For keyword Data. Data Tables are stores In the Dataset
'Create the primary object to hold both data tables
Dim AllKeyWordInfo As DataSet = New DataSet("AllKeywordInfo")
'Create a Datatable For keyword Data. Data Tables are stores In the Dataset
Dim KeywordData As DataTable = AllKeyWordInfo.Tables.Add("Keywords")
'Create a Datatable For URL Data.
Dim URLData As DataTable = AllKeyWordInfo.Tables.Add("URLMetrics")
'Add Columns to our Keyword datatable
KeywordData.Columns.Add("Keyword")
KeywordData.Columns.Add("SearchCount")
'Add Columns to URLDATA
URLData.Columns.Add("Keyword")
URLData.Columns.Add("URL")
URLData.Columns.Add("DA")
URLData.Columns.Add("PA")
'Creat a parent child relationship
AllKeyWordInfo.Relations.Add("ALLDATA", AllKeyWordInfo.Tables("Keywords").Columns("Keyword"), AllKeyWordInfo.Tables("URLMetrics").Columns("Keyword"))
'parent
KeywordData.Rows.Add("TESTEST", "1123829")
'children
URLData.Rows.Add("TESTEST", "288789")
URLData.Rows.Add("TESTEST", "asdsdsdd")
DataGridView1.DataSource = KeywordData
DataGridView2.DataSource = URLData
我想做的是在datagridview1中显示KeywordData表中的所有内容。当用户单击任何行(datagrid上启用了全行选择)时,我希望datagridview2显示该关键字的所有子行。每当用户切换datagridview1中的行时,它都会切换到datagridview2中正确的子行。这可能吗?关键在于绑定。对于完整的解决方案,包括创建
数据集
:
考虑到您已经有一个包含两个数据表的数据集
和一个数据关系
,这里是重要的部分:
'Bind the parent source to the parent table.
Me.BindingSource1.DataSource = data
Me.BindingSource1.DataMember = "Parent" 'This is the name of the parent DataTable.
'Bind the child source to the relationship.
Me.BindingSource2.DataSource = Me.BindingSource1
Me.BindingSource2.DataMember = "ParentChild" 'This is the name of the DataRelation.
'Bind the parent control to the parent source.
Me.DataGridView1.DataSource = Me.BindingSource1
'Bind the child control to the child source.
Me.DataGridView2.DataSource = Me.BindingSource2
在本例中,数据
是数据集
。请注意,父BindingSource
通过DataSet
绑定到父DataTable
,而子BindingSource
通过父BindingSource
绑定到DataRelation
,而不是绑定到子DataTable
还要注意,我的原始示例绑定到ComboBox
控件,但正如我在该线程中所说的,无论控件的类型如何,原理都是相同的。我编辑了上面的代码,改为使用DataGridView
控件