Search code examples
winformsvisual-c++c++-cli

Getting error C2440 when trying SqlConnection


Getting

Error C2440: 'initializing': cannot convert from 'System::Data::SqlClient::SqlConnection' to 'System::Data::SqlClient::SqlConnection ^'

for this line

    SqlConnection^ con = SqlConnection("c:\\project\\project\\database.db");

Would like to know why i'm getting this error and how to fix it, im using visual c++, winform ui


Solution

  • The error message should make clear exactly what is going wrong. You just have to look carefully, because it's a difference of a single character. Here it is again, with noise removed:

    cannot convert from 'SqlConnection' to 'SqlConnection ^'

    See that ^ character at the end? The compiler is saying it can't convert from an object (SqlConnection) to a managed pointer-to-object (SqlConnection^).

    To create a managed pointer-to-object, you would use the gcnew operator:

    SqlConnection^ con = gcnew SqlConnection("c:\\project\\project\\database.db");
    

    Or, if you don't actually need a pointer, just change the type of the con variable:

    SqlConnection con = SqlConnection("c:\\project\\project\\database.db");
    

    For more details, see: What does the caret (‘^’) mean in C++/CLI?