How to delete data in windows application C#?

In this tutorial you will learn how to insert, update, and delete data using window application form C#. For fronted we used window form application and for backend we used SQL server for database.

Here you will learn step by step delete operation.

Step 1.

In previous tutorial we were inserting the data in table using window form application. Now we will delete the same data with delete command. For that we will use previous window form.

Here we are just working on delete button.

delete

Step 2.

We already created table in SQL Server in previous tutorial. And record are already is there in table. So no need to create another table and we are working on same table record.

create table

Step 3.

Now move to window form application(Form1.cs) and add following namespace in coding window. Simply double click on window form.

	
	using System.Data.SqlClient;
	
namespace

Step 4.

Now create a connection string to connect with Database. Make your Connection globally like below so that you can access it anywhere in the form.

The connection string that includes the source database name, and other parameters needed to establish the initial connection.

	
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Data;
	using System.Drawing;
	using System.Linq;
	using System.Text;
	using System.Threading.Tasks;
	using System.Windows.Forms;

	using System.Data.SqlClient;

	namespace Intsert
	{
    	public partial class Form1 : Form
    	{
        	public Form1()
        	{
            	InitializeComponent();
        	}

        	//globaly define conection
        	SqlConnection con = new SqlConnection("data source=DESKTOP-F3B3CCJ\SQLEXPRESS; database=master; uid=sa; password=123456;");
        	
    	}
	}
	

Step 5.

Now move to window form design view and double click on delete button. Add following code on your delete button click.

We are deleting the data with unique column field and our unique filed is roll_no field.

	
	private void button3_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("delete student where roll_no='" + textBox2.Text + "'", con);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Data Deleted Successfully.");
            con.Close();
        }
	

Now run you window form application. Press f5 key from keyword or from start button in Visual Studio.

Now enter the any roll no and click on delete button.

insert message

Output

Now move to Microsoft SQL Server and see your records in table. For that run SQL Server select query.

One record deleted from table.

sql query
Advertisement here

Share this Page.