c# question code errors

I got a error:

A field initializer cannot reference the nonstatic field, method, or property

in this line of code

      private System.Data.SqlClient.SqlConnection Connection = CreateConnection();

I am converting from vb.net to c#
vbnetcoderAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Connect With a Mentor Billing EngineerCommented:
remove:
string strConnString = conString.ConnectionString;

and change:
con.ConnectionString = strConnString;

into:
con.ConnectionString = conString;
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
>CreateConnection();

I presume that the method you call there is part of the same class?
which needed to be a static method (of the same or another class), which is what the error message tells you.

0
 
Dale BurrellDirectorCommented:
change to

private System.Data.SqlClient.SqlConnection Connection = null;

and in the constructor put

Connection = CreateConnection();
0
 
vbnetcoderAuthor Commented:
Ok that worked but now this:

string strConnString = conString.ConnectionString;


Gives me the error


'string' does not contain a definition for 'ConnectionString'      

public class clsData
{
	private System.Data.SqlClient.SqlConnection Connection = null;
	private System.Data.SqlClient.SqlConnection CreateConnection()
	{

        string conString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();      
        string strConnString = conString.ConnectionString;

		System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
		con.ConnectionString = strConnString;

		if (con.State == ConnectionState.Closed)
		{
			con.Open();
		}

		return con;

	}

Open in new window

0
 
vbnetcoderAuthor Commented:
ty
0
All Courses

From novice to tech pro — start learning today.