Net-informations.com
SiteMap  | About    

How to add relations between tables in a Dataset

The DataSet contains DataTableCollection and their DataRelationCollection. The DataSet.Relations property is an instance of the DataRelationsCollection Object. We can create parent child data relations between DataTable using Datarelation Object. We can relate one or more column from different tables using DataRelation Object . The columns involved in the DataRelation should be identical data types. That is the parent and child column should be similar Data Types.




Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim adapter As New SqlDataAdapter
        Dim ds As New DataSet
        Dim firstSql As String
        Dim secondSql As String
		connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
		firstSql = "Your First SQL Statement Here"
		secondSql = "Your Second SQL Statement Here"
        connection = New SqlConnection(connetionString)
        Try
            connection.Open()
            command = New SqlCommand(firstSql, connection)
            adapter.SelectCommand = command
            adapter.Fill(ds, "Table1")

            adapter.SelectCommand.CommandText = secondSql
            adapter.Fill(ds, "Table2")

            adapter.Dispose()
            command.Dispose()
            connection.Close()
            'creating data relations
            Dim relation As DataRelation
            Dim table1Column As DataColumn
            Dim table2Column As DataColumn
            'retrieve column
            table1Column = ds.Tables("Table1").Columns(0)
            table2Column = ds.Tables("table2").Columns(0)
            'relating tables
            relation = New DataRelation("relation", table1Column, table2Column)
            'assign relation to dataset
            ds.Relations.Add(relation)

            MsgBox("Data relation completed")
        Catch ex As Exception
            MsgBox("Can not open connection ! ")
        End Try
    End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
firstSql = "Your First SQL Statement Here"
secondSql = "Your Second SQL Statement Here"

You have to replace the string with your real time variables.





net-informations.com (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.