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

22,161

Solution 1

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 guarantee disposal of your connection object and therefore prevent connection pool problems. :)

The reason you were getting the error in the fist place is that you were trying to assign a string value (ConfigurationManager.ConnectionStrings["connect"].ConnectionString) to a variable of type SqlConnection.

I suggest you learn more about variable typing, variable casting and type assignments in C#, it will make coding a much more pleasurable (less frustrating) experience.

Good Luck!

Solution 2

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

Solution 3

ConfigurationManager.ConnectionStrings["connect"].ConnectionString is a String to holds the connection information.

You need to create an instance of SqlConnection and pass in the connection string value.

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

Share:
22,161
Amruta
Author by

Amruta

Azure Team Lead

Updated on July 23, 2022

Comments

  • Amruta
    Amruta almost 2 years

    I am getting this error:

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

    for this code:

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

    How do I solve this problem? I am working with a Windows application.