In this article I will explain with an example, how to delete data from
MySQL database in ASP.Net using C# and VB.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing CustomerId of the Customer record to be deleted.
Button – For deleting the record.
The Button has been assigned with an OnClick event handler.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 60px">Id<br />
<asp:TextBox ID="txtId" runat="server" Width="50px" />
</td>
<td style="width: 200px">
<br />
<asp:Button Text="Delete" runat="server" OnClick="OnDelete" />
</td>
</tr>
</table>
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using MySql.Data.MySqlClient;
VB.Net
Imports System.Configuration
Imports MySql.Data.MySqlClient
Deleting from MySQL Database in ASP.Net
When Delete button is clicked, first the connection is read from Web.Config file.
Then, a connection to the database is established using the MySqlConnection and CustomerId value is fetched from the TextBoxes and is passed as parameter.
After that, the record referenced with
CustomerId is deleted from the
MySQL database using
ExecuteNonQuery method.
Finally, based on whether record is deleted or not, an appropriate message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnDelete(object sender, EventArgs e)
{
string sql = "DELETE FROM Customers WHERE CustomerId=@CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(sql,con))
{
cmd.Parameters.AddWithValue("@CustomerId", txtId.Text);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer record deleted.');",true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer not found.');",true);
}
}
}
}
VB.Net
Protected Sub OnDelete(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String = "DELETE FROM Customers WHERE CustomerId=@CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As MySqlConnection = New MySqlConnection(constr)
Using cmd As MySqlCommand = New MySqlCommand(sql, con)
cmd.Parameters.AddWithValue("@CustomerId", txtId.Text)
con.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
con.Close()
If i > 0 Then
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Customer record deleted.');",True)
Else
ClientScript.RegisterStartupScript(Me.[GetType](), "alert", "alert('Customer not found.');",True)
End If
End Using
End Using
End Sub
Screenshot
Downloads