Click here to Skip to main content
15,900,714 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
class General
    {
        SqlConnection con = new SqlConnection();
        public SqlConnection cn()
        {

            con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
            return con;
        }

        private void cnopen()
        {
            if (con.State == con.Open()) //Operator '==' cannot be applied to  //operands of type 'System.Data.ConnectionState' 

            {
                con.Close();
            }
            con.Open();
        }      
    }
Posted
Updated 1-Sep-12 20:44pm
v2

Create a new .cs file and creat there a class as like..
C#
public class databaseConnection
{
    public static string connectionString = "useYourConnectionStringHere";

}

then in your main class use it as..
C#
SqlConnection con;
private void connect()
{
    String s = databaseConnection.connectionString;
    con = new SqlConnection(s);
    con.Open();
}
private void disConnect()
{
    con.Close();
}

then use it in your method or button event as like as..
C#
try
{
  connect();
 .
 .  //use code for retrieving values from database here 
 .
 .
}
catch(Exception e)
{
}
 
Share this answer
 
Comments
D-Kishore 3-Sep-12 1:45am    
good 5:)
try
C#
if(con.State == ConnectionState.Open)
{
   con.Close();
}
 
Share this answer
 
Open does not return anything (see here[^])

If you want to check the connection.state you have to do it after you opened it...
 
Share this answer
 
Try This
class General
{
     SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;);

          public void cnopen()
            {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
          //if your connection is opened already then this if block do nothing 
          //if your connection is closed then this if block Open your connection.
           }
          public void cnclose()
            {
            if (con.State == ConnectionState.Open)
            {
                con.Close();
            }
          //if your connection is Close already then this if block do nothing 
          //if your connection is Opened then this if block Close your connection.
           }

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900