AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

How to delete record in c# using the connected approach

By pushpam abhishek
Listen to this article

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();
    }
}

If a matching row is found, it is removed from the table.

Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments