What is wrong with the scope in the following code?
namespace t2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
////// string connectionString = "Data Source=A-63A9D4D7E7834\\SQLEXPRESS;Initial Catalog=Test1;Integrated Security=True";
//connection string i taken from the file class1.cs static class.
try
{
string commandString = "Select * from Table_1";
SqlConnection conn = new SqlConnection(Class1.connection);
SqlCommand command = new SqlCommand(commandString, conn);
conn.Open();
// Start a local transaction.
SqlTransaction sqlTran = conn.BeginTransaction();
command.Transaction = sqlTran;
try
{
SqlDataReader reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}//try ends here.
catch (SqlException ex)
{
//Console.WriteLine(ex.Message);
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
// Throws an InvalidOperationException if the connection
// is closed or the transaction has already been rolled
// back on the server.
Response.Write(exRollback.Message.ToString());
}
// <snipped> build error message
}//sql catch ends here
catch (Exception all)
{
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
// Throws an InvalidOperationException if the connection
// is closed or the transaction has already been rolled
// back on the server.
Response.Write(exRollback.Message.ToString());
}
Response.Write(all.Message.ToString());
}//catch all ends
}//main try
finally
{
// Commit the transaction.
sqlTran.Commit();
reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();
}//finally ends
}//page load method ends
Errors displayed are:
Error 1 The name 'sqlTran' does not exist in the current context D:\DOCUMENTSS\Visual Studio 2008\Projects\t2\t2\Default.aspx.cs 162 17 t2
Error 2 The name 'reader' does not exist in the current context D:\DOCUMENTSS\Visual Studio 2008\Projects\t2\t2\Default.aspx.cs 166 17 t2
Error 3 The name 'reader' does not exist in the current context D:\DOCUMENTSS\Visual Studio 2008\Projects\t2\t2\Default.aspx.cs 167 17 t2
Error 4 The name 'conn' does not exist in the current context D:\DOCUMENTSS\Visual Studio 2008\Projects\t2\t2\Default.aspx.cs 169 17 t2
Error 5 The name 'conn' does not exist in the current context D:\DOCUMENTSS\Visual Studio 2008\Projects\t2\t2\Default.aspx.cs 170 17 t2
Those variables are declared inside the try portions of your code. Inside the catch {} portions, those variables do not exist. To fix the problem, you need to declare the variables outside the try block (setting them to null), and then you can instantiate them in try block. Be sure to check for null values in the catch blocks.