As @NotPoliticallyCorrect has stated - you need to step through your code with the debugger, examine variables and program flow and you might be able to understand what is going on. This article should help you
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[
^]
Your use of Try-Catch is not really sensible - you are not adding anything to the exception before escalating it, so just let it percolate up through the thread. This article might help you
Exception Handling Best Practices in .NET[
^]
Your problem is the line
connection = DB.DisconnectFromDB(connection);
I have no idea what
DB
is but I'm guessing that
DisconnectFromDB
does what it says and disconnects your carefully created connection!
On a final note - I wouldn't pass the connection around like that. Encapsulate the
connection
variable in your class. For a simplistic example...
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace Sandbox
{
public class DbClass
{
private SqlConnection connection;
public bool ConnectToDb()
{
if (connection == null)
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectToDB"].ConnectionString);
if (connection.State != ConnectionState.Open)
connection.Open();
return (connection.State == ConnectionState.Open);
}
}
}
Which I can call like this:
var xdb = new DbClass();
var b = xdb.ConnectToDb();
Debug.Print(b.ToString());
- meaning the calling module does not need to know anything about
System.Data.SqlClient
... which makes life a lot easier if I was to switch database provider