How to multiple tables in Dataset - Sql Server

The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The SqlDataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method in the SqlDataAdapter for populating data in a Dataset.

We can populate Dataset with more than one table at a time using SqlDataAdapter Object . The following VB.NET source code shows how to a single SqlDataAdapter fill Dataset with multiple tables.

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 i As Integer
        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)


            command = New SqlCommand(firstSql, connection)
            adapter.SelectCommand = command
            adapter.Fill(ds, "First Table")

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


            'retrieve first table data
            For i = 0 To ds.Tables(0).Rows.Count - 1
                MsgBox(ds.Tables(0).Rows(i).Item(0) & "  --  " & ds.Tables(0).Rows(i).Item(1))
            'retrieve second table data
            For i = 0 To ds.Tables(1).Rows.Count - 1
                MsgBox(ds.Tables(1).Rows(i).Item(0) & "  --  " & ds.Tables(1).Rows(i).Item(1))

        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"
sql = "Your SQL Statement Here"

You have to replace the string with your real time variables. (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About