How to bind populate GridView using DataSet in ASP.Net using C# and VB.Net?

How to bind (populate) GridView using DataSet in ASP.Net using C# and VB.Net?

In this post, How to bind (populate) GridView using DataSet in ASP.Net using C# and VB.Net?. Thus multiple GridViews will be populated using a single DataSet in ASP.Net. DataSet is a collection of DataTables and is capable to hold data from multiple tables.

The HTML Markup consists of one GridViews which will be populated using the DataSet.

<asp:GridView ID="gdvCustomer" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText="Contact Name" ItemStyle-Width="150px" />
        <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100px" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100px" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Namespaces

VB.Net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

C#

 

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        string query = "SELECT TOP 5 ContactName, City, Country FROM Customers;";
 
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds);
                        gdvCustomer.DataSource = ds.Tables[0];
                        gdvCustomer.DataBind();
                    }
                }
            }
        }
    }
}

VB.Net

 

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim query As String = "SELECT TOP 5 ContactName, City, Country FROM Customers;"
 
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand(query)
                Using sda As New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using ds As New DataSet()
                        sda.Fill(ds)
                        gdvCustomer.DataSource = ds.Tables(0)
                        gdvCustomer.DataBind()
                    End Using
                End Using
            End Using
        End Using
    End If
End Sub

2021-10-03