We can manage transactions at the database level through a transaction object.There are three types of transaction objects in ADO.NET.They are SqlTransaction, OracleTransaction, and OleDbTransaction. The following code uses a DataGrid control to display a list of contacts from the Contacts database. The DataGrid control includes a column of buttons that allow the user to delete contacts. The DeleteContact function uses a transaction to ensure that a contact’s calls are deleted if the contact is deleted. This helps ensure the integrity of the database.
private void Page_Load(object sender, System.EventArgs e) { // Fill the data set. adptContacts.Fill(dsContacts); // Bind to the data set. grdContacts.DataBind(); }
private void grdContacts_ItemCommand(object sender, System.Web.UI.WebControls.DataGridCommandEventArgs e) { // If the Delete button was clicked. if (e.CommandName == "Delete") { int intContactID; // Get selected row's ContactID. intContactID = Convert.ToInt16(grdContacts.Items [e.Item.ItemIndex].Cells[3].Text); // Delete the contact information. lblStatus.Text = DeleteContact(intContactID); } // Refresh the data set. adptContacts.Fill(dsContacts); // Refresh the data grid. grdContacts.DataBind(); }
string DeleteContact(int intContactID) { // Open the database connection. ContactMgmt.Open(); // Declare a transaction object. SqlTransaction transDelete; // Create the tranasction. transDelete = ContactMgmt.BeginTransaction (IsolationLevel.ReadCommitted); // Create the command to delete from Contacts table. SqlCommand cmdDelete = new SqlCommand("DELETE FROM Contacts" + " WHERE ContactID=" + intContactID.ToString(), ContactMgmt, transDelete); // Execute the commands try { int intRows; // Delete row from Contacts table. intRows = cmdDelete.ExecuteNonQuery(); // Delete Calls for this ContactID. cmdDelete.CommandText = "DELETE FROM Calls WHERE " + " ContactID=" + intContactID.ToString(); intRows = intRows + cmdDelete.ExecuteNonQuery(); // Commit the transaction. transDelete.Commit(); // Return success message. return intRows.ToString() + " deleted."; } catch { // Restore the database state if there was an error. transDelete.Rollback(); // Return error message. return "Contact could not be deleted."; } finally { // Close the database. ContactMgmt.Close(); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|