In this article I will explain with an example, how to delete data from database in Windows Forms (WinForms) Applications 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.
Form Design
The following Form consists of:
TextBox – For capturing CustomerId of the Customer record to be deleted.
Button – For deleting the record.
Adding ConnectionString to the App.Config file
You need to add the Connection String in the ConnectionStrings section of the App.Config file in the following way.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="constr" connectionString="Data Source=.\SQL2022;DataBase=AjaxSamples;Integrated Security = true; " providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Deleting the record from Database in Windows Forms
When Delete button is clicked, the connection string is fetched from the App.Config file and object of SqlConnection class is created using it.
Then, an object of SqlCommand class is created and the DELETE query is passed to it as parameter.
The value of the CustomerId is added as parameter to SqlCommand object.
And the connection is opened and the ExecuteNonQuery function is executed.
Finally, based on whether record is deleted or not, an appropriate message displayed using MessageBox class.
C#
private void OnDelete(object sender, EventArgs e)
{
string query = "DELETE FROM Customers WHERE CustomerId = @CustomerId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@CustomerId", txtId.Text);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
MessageBox.Show("Customer record deleted.");
}
else
{
MessageBox.Show("Customer not found.");
}
}
}
}
VB.Net
Private Sub OnDelete(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim query As String = "DELETE FROM Customers WHERE CustomerId = @CustomerId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@CustomerId", txtId.Text)
con.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
con.Close()
If i > 0 Then
MessageBox.Show("Customer record deleted.")
Else
MessageBox.Show("Customer not found.")
End If
End Using
End Using
End Sub
Screenshot
Downloads