Cannot implicitly convert type 'string' to 'System.Data.SqlClient.Sqlconnection'

I get this error:

cannot implicitly convert type 'string' to 'System.Data.SqlClient.Sqlconnection'

for this code:

SqlConnection con1 = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;

How to solve this problem? I am working with a windows application.

+3
source share
4 answers

This is what you need:

using(SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
{
   // do something with con1
}

Note: this is better than the other answers because it includes another hint: use the using keyword to ensure that your connection object is deleted and therefore prevent problems with the connection pool. :)

, , , (ConfigurationManager.ConnectionStrings [ "connect" ]. ConnectionString) SqlConnection.

, #, ( ).

!

+14
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
+3

ConfigurationManager.ConnectionStrings["connect"].ConnectionString - , .

SqlConnection .

SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);

+1
using (System.Data.SqlClient.SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString)) { 
    con.Open(); 
    SqlCommand cmd = new SqlCommand(); 
    string expression = "Parameter value"; 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.CommandText = "Your Stored Procedure"; 
    cmd.Parameters.Add("Your Parameter Name", 
                SqlDbType.VarChar).Value = expression;    
    cmd.Connection = con; 
    using (IDataReader dr = cmd.ExecuteReader()) 
    { 
        if (dr.Read()) 
        { 
        } 
    } 
}
0

All Articles