I am using Begining C# although I am fluent in VB6 to get up to speed however I am getting the error "Does not exist in current context"for sqltrans.Rollback.
I have 3 labels and 3 text boxes - textbox1 - 3. It works when I comment the rollback out though. Am I missing something basic or is the code wrong. I could easily code it out and carry on but that would not be helpful later on of course!
Thank you in advance...
[code]
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
using
System.Data.SqlClient;
namespace
WindowsFormsApplication1
{
public partial class Transaction : Form
{
public Transaction()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"
data source = .\sqlexpress;
integrated security = true;
database = Northwind
"
);
//INSERT statement
string sqlins = @"
insert into customers(customerid,companyname)
values(@newcustid, @newconame) "
;
//DELETE statement
string sqldel = @"
delete from customers
where customerid = @oldcustid"
;
try
{
//open connection
conn.Open();
//begin transaction
SqlTransaction sqltrans = conn.BeginTransaction();
//create insert command
SqlCommand cmdins = conn.CreateCommand();
cmdins.CommandText = sqlins;
cmdins.Transaction = sqltrans;
cmdins.Parameters.Add(
"@newcustid",
System.Data.
SqlDbType.NVarChar, 5);
cmdins.Parameters.Add(
"@newconame",
System.Data.
SqlDbType.NVarChar, 30);
//create delete command
SqlCommand cmddel = conn.CreateCommand();
cmddel.CommandText = sqldel;
cmddel.Transaction = sqltrans;
cmddel.Parameters.Add(
"@oldcustid",
System.Data.
SqlDbType.NVarChar, 5);
//add customer
cmdins.Parameters[
"@newcustid"].Value = textBox1.Text;
cmdins.Parameters[
"@newconame"].Value = textBox2.Text;
cmdins.ExecuteNonQuery();
//delete customer
cmddel.Parameters[
"@oldcustid"].Value = textBox3.Text;
cmddel.ExecuteNonQuery();
//commit transaction
sqltrans.Commit();
//no exception, transaction committed, give message
MessageBox.Show("Transaction committed");
}
catch (System.Data.SqlClient.SqlException ex)
{
//roll back transaction
sqltrans.Rollback();
MessageBox.Show("Transaction rolled back\n" + ex.Message, "Error");
}
finally
{
//close connection
conn.Close();
}
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
[/code]