在一个数据网格视图中显示父数据表并在另一个数据表中显示子数据表元素?

Showing parent datatable in one datagridview and show child datatable elements in another?

您好,我创建了一个数据集和两个数据table。 URLData table 通过关键字列作为 KeywordData table 的父级。

'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 中显示关键字数据 table 中的所有内容。当用户单击任何行时(在数据网格上启用了整行 select),我希望 datagridview2 显示该关键字的所有子行。每当用户在 datagridview1 中切换行时,它都会切换到 datagridview2 中的适当子行。这可能吗?

诀窍在于绑定。 Click here 完整解决方案,包括创建 DataSet:

这是重要的部分,考虑到您已经有一个包含两个 DataTables 和一个 DataRelationDataSet

'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

在这种情况下,data 就是 DataSet。请注意,parent BindingSource 通过 DataSet 绑定到 parent DataTable,而 child BindingSource 绑定到DataRelation 通过 parent BindingSource,而不是绑定到 child DataTable

另请注意,我的原始示例绑定到 ComboBox 控件,但正如我在该线程中所说,无论控件的类型如何,原理都是相同的。我编辑了上面的代码,改为使用 DataGridView 控件。