ASP.NET - Databases - Delete
<!DOCTYPE html>
<html>
<head>
<title>Delete Records</title>
</head>
<body>
<h2>Delete Records</h2>
<form method="post">
Enter the ID of the record you want to delete: <input type="text" name="id" /><br /><br />
<input type="submit" name="delete" value="Delete" />
</form>
</body>
</html>
Code-behind (C#):
protected void Page_Load(object sender, EventArgs e)
{
// Check if the form has been submitted
if (IsPostBack)
{
// Get the ID of the record to be deleted
int id = int.Parse(Request.Form["id"]);
// Create a connection to the Access database
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb";
OleDbConnection connection = new OleDbConnection(connectionString);
try
{
// Open the connection
connection.Open();
// Create a SQL statement to delete the record
string sql = "DELETE FROM MyTable WHERE ID = @id";
// Create a command object with the SQL statement and the connection
OleDbCommand command = new OleDbCommand(sql, connection);
// Add a parameter for the ID value
command.Parameters.AddWithValue("@id", id);
// Execute the SQL statement
int rowsAffected = command.ExecuteNonQuery();
// Check if any rows were affected
if (rowsAffected > 0)
{
// Display a message indicating the record was deleted
Response.Write("<p>The record with ID " + id + " has been deleted.</p>");
}
else
{
// Display a message indicating the record was not found
Response.Write("<p>The record with ID " + id + " was not found.</p>");
}
}
catch (Exception ex)
{
// Display an error message
Response.Write("<p>Error: " + ex.Message + "</p>");
}
finally
{
// Close the connection
connection.Close();
}
}
}