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

Mansour_Dalir 1,716 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

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,877 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,663 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 29,101 Reputation points Microsoft Vendor
    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