How to relationship two DataTable and get Results in the third DataTable?

Mansour_Dalir 2,036 Reputation points
2023-05-20T10:36:39.65+00:00

Untitled

Hello.

I want to get the filtered result in the third DataTable after relationship the two DataTables. Thank

        Dim dtParent As New DataTable
        Dim dtChild As New DataTable
        Dim dtResult As New DataTable
        dtParent.Columns.Add("filter")
        dtParent.Columns.Add("words")
        dtParent.Rows.Add({"a", "w1"})
        dtParent.Rows.Add({"b", "w2"})
        dtParent.Rows.Add({"c", "w3"})
        dtParent.Rows.Add({"k", "w4"})
        dtParent.Rows.Add({"m", "w5"})
        dtChild.Columns.Add("Filter")
        dtChild.Rows.Add("k")
        dtChild.Rows.Add("b")
        dtChild.Rows.Add("c")
        

tags: vb.net DataTable DataGridView

Developer technologies | VB
Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Jiachen Li-MSFT 34,231 Reputation points Microsoft External Staff
    2023-05-22T05:34:10.4333333+00:00

    Hi @Mansour_Dalir ,

    If you want to use DataRelation Class, you can refer to the following code.

            Dim dtset As New DataSet
            dtset.Tables.Add(dtParent)
            dtset.Tables.Add(dtChild)
    
            dtResult.Columns.Add("filter")
            dtResult.Columns.Add("words")
    
            Dim relation As New DataRelation("ParentChildRelation", dtParent.Columns("filter"), dtChild.Columns("Filter"))
    
            dtset.Relations.Add(relation)
    
            For Each childRow As DataRow In dtChild.Rows
                Dim filterValue As String = childRow("Filter").ToString()
                Dim parentRows As DataRow() = childRow.GetParentRows(relation)
    
                For Each parentRow As DataRow In parentRows
                    dtResult.Rows.Add(parentRow("filter"), parentRow("words"))
                Next
            Next
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.