How to Dataset with Sql Server

The DataSet in ADO.NET contains a copy of the data that we retrieve from the data source using SQL statements. To populate the DataSet with data, we can use the SqlDataAdapter class, which acts as a bridge between the data source and the DataSet.

Fill method

The SqlDataAdapter provides the Fill method, which is used to populate one or more DataTables within the DataSet. The Fill method takes as parameters the DataSet object and the name of the DataTable(s) to be filled. It retrieves the data from the data source using the specified SQL statement or stored procedure and fills the DataTable(s) in the DataSet with the retrieved data.

Here's an example of how to use the SqlDataAdapter and Fill method to populate a DataSet:

Full Source VB.NET
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 sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds) adapter.Dispose() command.Dispose() connection.Close() 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)) Next Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

Conclusion

Please note that the example above uses SQL Server as the data source, but you can also use other data providers and their corresponding classes, such as OleDbDataAdapter for OLE DB data sources, or OdbcDataAdapter for ODBC data sources, to populate a DataSet in a similar manner.