How to delete record in c# using the connected approach

How to delete record in c# using the connected approach,delete a database record using the connected approach,window from,DeletingRecordsConnected
Share it:

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 it:

adonet

Windows Forms

Post A Comment:

0 comments: