2016-07-22 77 views
0

嗨我已經創建了一個數據集和兩個數據表。 URLData表通過關鍵字列被關聯到KeywordData表。在一個datagridview中顯示父數據表並在另一個數據表中顯示子數據表元素?

'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中關鍵字數據表的所有內容。當用戶單擊任何行(在數據網格上啓用了全行選擇)時,我希望datagridview2顯示該關鍵字的所有子行。每當用戶切換datagridview1中的行時,它都會切換到datagridview2中的適當子行。這可能嗎?

回答

1

訣竅在於綁定。 Click here了完整的解決方案,這包括創建DataSet

這裏的重要組成部分,考慮到你已經有包含兩個DataTables一個DataSetDataRelation

'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 

在這種情況下,dataDataSet 。請注意,父BindingSource通過DataSet綁定到父DataTable,而子BindingSource通過父BindingSource綁定到DataRelation,而不是綁定到子DataTable

另請注意,我的原始示例綁定到ComboBox控件,但正如我在該線程中所說的,無論控件的類型如何,原理都是相同的。我編輯了上面的代碼來代替使用DataGridView控件。

+0

完美的作品謝謝你! –

相關問題