Execute database commands within a single local transaction. You can test rollback and partial rollback. : Transaction « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Begin Local Transactions</title>
</head>
<body>
    <div id="pageContent">    
        <form id="form1" runat="server">
          <h2>Click this button to display current data.</h2>
        <asp:Button id="ShowButton" runat="server" Text="Show Data" OnClick="ShowButton_Click"></asp:Button>
        
        <h2>Click this button to execute a transaction</h2>
        <asp:Button id="ExecuteButton" runat="server" Text="Execute Transaction" OnClick="ExecuteButton_Click"></asp:Button>
        <asp:CheckBox id="CheckBox_Partial" runat="server" Text="Partial Rollback"></asp:CheckBox>
        <h2>Click this button to restore the original state of data</h2>
        <asp:Button id="RestoreButton" runat="server" Text="Restore" OnClick="RestoreButton_Click"></asp:Button>
        <hr>
        <asp:Label runat="server" id="lblMessage" /> 
        <br>
        <asp:DataGrid id="grid" runat="server" visible="False" CellPadding="4" GridLines="None" ForeColor="#333333" CssClass="shadowed" font-size="X-Small" font-names="verdana">
          <AlternatingItemStyle BackColor="White" />
          <ItemStyle BackColor="#EFF3FB" />
          <HeaderStyle ForeColor="White" BackColor="#507CD1" Font-Bold="True" />
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <EditItemStyle BackColor="#2461BF" />
                <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        </asp:DataGrid>
        </form>
    </div>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
    private const string ConnString = "SERVER=(local);DATABASE=northwind;Trusted_Connection=yes;";
    private const string SelectCmd = "SELECT employeeid, firstname, lastname FROM Employees";
    private const string UpdateCmd = "UPDATE Employees SET firstname='Michela' WHERE EmployeeID=1";
    private const string InsertCmd = "INSERT INTO Employees (firstname,lastname) VALUES ('Dino', 'Esposito')";

    protected void ShowButton_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = SelectCmd;

            conn.Open();
            grid.DataSource = cmd.ExecuteReader();
            grid.DataBind();
            grid.Visible = true;
            conn.Close();
        }
    }

    protected void ExecuteButton_Click(object sender, EventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConnString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;

            conn.Open();
            SqlTransaction t = conn.BeginTransaction();
            cmd.Transaction = t;

            try
            {
                cmd.CommandText = UpdateCmd;
                cmd.ExecuteNonQuery();
                t.Save("AfterUpdate");

                cmd.CommandText = InsertCmd;
                cmd.ExecuteNonQuery();

                if (CheckBox_Partial.Checked)
                    t.Rollback("AfterUpdate");

                t.Commit();

                lblMessage.Text = "<b>Done</b>";
                grid.Visible = false;
            }
            catch (Exception exc)
            {
                t.Rollback();
                lblMessage.Text = "<b>Error occurred: </b>" + exc.Message;
            }
        }
    }

    protected void RestoreButton_Click(object sender, EventArgs e) {
        using (SqlConnection conn = new SqlConnection(ConnString)) {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            conn.Open();
            SqlTransaction t = conn.BeginTransaction();
            cmd.Transaction = t;

            try {
                cmd.CommandText = "UPDATE Employees SET firstname='Nancy' WHERE EmployeeID=1";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "DELETE FROM Employees WHERE EmployeeID >9";
                cmd.ExecuteNonQuery();
                t.Commit();
                lblMessage.Text = "<b>Done</b>";
                grid.Visible = false;
            }
            catch (Exception exc)
            {
                t.Rollback();
                lblMessage.Text = "<b>Error occurred: </b>" + exc.Message;
            }
        }
    }
}








18.57.Transaction
18.57.1.Use transaction to group operations (VB.net)
18.57.2.Execute database commands within a single local transaction. You can test rollback and partial rollback.