Deleting Record in c#: Connected Approach
We will now delete a database record using the connected approach. The steps are the same as inserting a record while connected to a database that uses the DbCommand.ExecuteNonQuery() method.
- Create a Connection
- Create a Command
- Specify connection string to Connection
- Specify Connection that the Command will use
- Specify the DELETE Statement for the CommandText of the Command
- Add values to command parameters if any
- Open Connection
- Execute the command
- Close Connection
Let's create a simple application that allows you to specify the StudentId and delete the corresponding record having that ID. Create a new Windows Forms Application and name it DeletingRecordsConnected. Add a label and text box for the StudentID and a button that will execute the commands. Name the text box studentIdTextBox and the button as delete button.
Double click the button to generate an event handler for its Click event. Be sure to import the System.Data.SqlClient namespace. Use the following code for the event handler.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
"Initial Catalog=University;Integrated Security=SSPI";
command.Connection = connection;
command.CommandText = "DELETE FROM Students WHERE StudentID=@StudentID";
command.Parameters.AddWithValue("@StudentID", studentIdTextBox.Text);
try
{
connection.Open();
int result = command.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("Student was removed!");
else
MessageBox.Show("Can't find student.");
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured.");
}
finally
{
connection.Close();
}
}
Do you know:-
- How to Retrieve data using dataset in c#
- The Command Class | C# | TrickCode
- C# DataReader ADO.NET |Trickcode
- What is disconnected data access?
- how to Adding Parameters to Commands
- SQL Basics?
- What is Database Preparations?
- SQL vs NoSQL or MySQL vs MongoDB
- What is data provider in C#?
- What is connection string C#?
- [SQL] SELECT Statement | Example
- how to get return value from stored procedure in sql server
- how to prevent sql injection attacks
- What is Database? What is SQL?
- C#.Net How To: Send email in asp.net using c#
If you like the tutorial, then please share this tutorial with your friends on social media
Related Articles
This post first appeared on Learn To Asp.net,Visual Code,Nodes,Angular,technews :TrickCode, please read the originial post: here