In this article I will explain with an example, how to use ExecuteReader method of MySQLCommand in ASP.Net using C# and VB.Net.
Download and Install the MySQL Connector
You will need to download and install the
MySQL Connector in order to connect to the
MySQL database in ASP.Net.
Database
I have made use of the following table Customers with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of following control:
GridView – For displaying data.
The GridView consists of three BoundField columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="Name" HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.MySqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.MySqlClient
Fetching Data using ExecuteReader in ASP.Net
Inside the Page Load event handler, the BindGrid method is called.
BindGrid
Inside the BindGrid method, the connection string is fetched from the Web.Config file and object of MySqlConnection class is created using it.
Then, an object of MySqlCommand class is created and the SELECT query is passed to it as parameter.
And the connection is opened and the ExecuteReader method is executed and fetched data is assigned to the DataSource property of the GridView.
Finally, the GridView is populated.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(sql, con))
{
con.Open();
gvCustomers.DataSource = cmd.ExecuteReader();
gvCustomers.DataBind();
con.Close();
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim sql As String = "SELECT CustomerId, Name, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand(sql, con)
cmd.Connection = con
con.Open()
gvCustomers.DataSource = cmd.ExecuteReader()
gvCustomers.DataBind()
con.Close()
End Using
End Using
End Sub
Screenshot
Downloads