In this article I will explain how to perform select, insert, edit, update, delete in GridView using MySQL database in ASP.Net using C# and VB.Net.
This process is also known as CRUD i.e. Create, Read, Update and Delete in GridView with MySQL database backend in ASP.Net.
 
 
Using MySQL with ASP.Net
This portion is extensively covered in my article Use and connect to MySQL Database in ASP.Net Application using MySQLConnector.
 
 
Database
I have made use of the following table Customers with the schema as follows.
 
ASP.Net MySQL CRUD: Select Insert Edit Update and Delete in GridView using MySQL database in ASP.Net
 
I have already inserted few records in the table.
ASP.Net MySQL CRUD: Select Insert Edit Update and Delete in GridView using MySQL database in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
         Download SQL file
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView with multiple event handlers assigned which will be discussed later.
The GridView has a CommandField column which will display the command buttons i.e. Edit, Update, Cancel and Delete.
Below the GridView there’s a Form which will allow us to insert data to the MySQL database table.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="CustomerId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting" EmptyDataText="No records has been added.">
<Columns>
    <asp:TemplateField HeaderText="Name" ItemStyle-Width="150">
        <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
        <ItemTemplate>
            <asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
        </EditItemTemplate>
    </asp:TemplateField>
    <asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
</asp:GridView>
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
    <td style="width: 150px">
        Name:<br />
        <asp:TextBox ID="txtName" runat="server" Width="140" />
    </td>
    <td style="width: 150px">
        Country:<br />
        <asp:TextBox ID="txtCountry" runat="server" Width="140" />
    </td>
    <td style="width: 100px">
        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
    </td>
</tr>
</table>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using MySql.Data.MySqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports MySql.Data.MySqlClient
 
 
Binding the GridView with records from MySQL Database Table
The GridView is populated from the database inside the Page Load event of the page.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Customers"))
        {
            using (MySqlDataAdapter sda = new MySqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
 
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 constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New MySqlConnection(constr)
        Using cmd As New MySqlCommand("SELECT * FROM Customers")
            Using sda As New MySqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
 
Following is the GridView containing records.
ASP.Net MySQL CRUD: Select Insert Edit Update and Delete in GridView using MySQL database in ASP.Net
 
For the GridView I have set EmptyDataText to display message when no records are present.
ASP.Net MySQL CRUD: Select Insert Edit Update and Delete in GridView using MySQL database in ASP.Net
 
 
Inserting records to GridView
The following event handler is executed when the Add Button is clicked. The name and the country values are fetched from their respective TextBoxes and then the record is inserted into the MySQL database table and the GridView is again populated with data by making call to the BindGrid method.
C#
protected void Insert(object sender, EventArgs e)
{
    string name = txtName.Text;
    string country = txtCountry.Text;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Customers (Name, Country) VALUES (@Name, @Country)"))
        {
            using (MySqlDataAdapter sda = new MySqlDataAdapter())
            {
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Country", country);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    this.BindGrid();
}
 
VB.Net
Protected Sub Insert(sender As Object, e As EventArgs)
    Dim name As String = txtName.Text
    Dim country As String = txtCountry.Text
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New MySqlConnection(constr)
        Using cmd As New MySqlCommand("INSERT INTO Customers (Name, Country) VALUES (@Name, @Country)")
            Using sda As New MySqlDataAdapter()
                cmd.Parameters.AddWithValue("@Name", name)
                cmd.Parameters.AddWithValue("@Country", country)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Me.BindGrid()
End Sub
 
 
Editing and Updating GridView records
Edit
When the Edit Button is clicked, the GridView’s OnRowEditing event handler is triggered. Here simply the EditIndex of the GridView is updated with the Row Index of the GridView Row to be edited.
C#
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowEditing(sender As Object, e As GridViewEditEventArgs)
    GridView1.EditIndex = e.NewEditIndex
    Me.BindGrid()
End Sub
 
Update
When the Update Button is clicked, the GridView’s OnRowUpdating event handler is triggered.
CustomerId which is the primary key is fetched from the DataKey property of GridView while the Name and Country fields are fetched from their respective TextBoxes and an Update query is executed over the MySQL database table.
For more details on DataKeys please refer my article DataKeyNames in GridView example in ASP.Net.
C#
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];
    int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    string name = (row.FindControl("txtName") as TextBox).Text;
    string country = (row.FindControl("txtCountry") as TextBox).Text;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        using (MySqlCommand cmd = new MySqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId"))
        {
            using (MySqlDataAdapter sda = new MySqlDataAdapter())
            {
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                cmd.Parameters.AddWithValue("@Name", name);
                cmd.Parameters.AddWithValue("@Country", country);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    GridView1.EditIndex = -1;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowUpdating(sender As Object, e As GridViewUpdateEventArgs)
    Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
    Dim customerId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
    Dim name As String = TryCast(row.FindControl("txtName"), TextBox).Text
    Dim country As String = TryCast(row.FindControl("txtCountry"), TextBox).Text
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New MySqlConnection(constr)
        Using cmd As New MySqlCommand("UPDATE Customers SET Name = @Name, Country = @Country WHERE CustomerId = @CustomerId")
            Using sda As New MySqlDataAdapter()
                cmd.Parameters.AddWithValue("@CustomerId", customerId)
                cmd.Parameters.AddWithValue("@Name", name)
                cmd.Parameters.AddWithValue("@Country", country)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
               con.Close()
            End Using
        End Using
    End Using
    GridView1.EditIndex = -1
    Me.BindGrid()
End Sub
 
Cancel Edit
When the Cancel Button is clicked, the GridView’s OnRowCancelingEdit event handler is triggered. Here the EditIndex is set to -1 and the GridView is populated with data.
C#
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
    GridView1.EditIndex = -1;
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowCancelingEdit(sender As Object, e As EventArgs)
    GridView1.EditIndex = -1
    Me.BindGrid()
End Sub
 
ASP.Net MySQL CRUD: Select Insert Edit Update and Delete in GridView using MySQL database in ASP.Net
 
 
Deleting GridView records
When the Delete Button is clicked, the GridView’s OnRowDeleting event handler is triggered.
CustomerId which is the primary key is fetched from the DataKey property of GridView and using the CustomerId the record is deleted from the MySQL database table.
C#
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        using (MySqlCommand cmd = new MySqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId"))
        {
            using (MySqlDataAdapter sda = new MySqlDataAdapter())
            {
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    this.BindGrid();
}
 
VB.Net
Protected Sub OnRowDeleting(sender As Object, e As GridViewDeleteEventArgs)
    Dim customerId As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Values(0))
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New MySqlConnection(constr)
        Using cmd As New MySqlCommand("DELETE FROM Customers WHERE CustomerId = @CustomerId")
            Using sda As New MySqlDataAdapter()
                cmd.Parameters.AddWithValue("@CustomerId", customerId)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Using
    Me.BindGrid()
End Sub
 
In order to display a confirmation message when deleting row, I have made use of OnRowDataBound event handler where I have first determined the Delete Button and then I have attach the JavaScript Confirm to its client side Click event handler.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
    {
        (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
    }
}
 
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow AndAlso e.Row.RowIndex <> GridView1.EditIndex Then
        TryCast(e.Row.Cells(2).Controls(2), LinkButton).Attributes("onclick") = "return confirm('Do you want to delete this row?');"
    End If
End Sub
 
ASP.Net MySQL CRUD: Select Insert Edit Update and Delete in GridView using MySQL database in ASP.Net
 
 
Downloads