We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,621 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

A field initializer cannot reference the non-static field, method, or property?

Hello to all,
I am calling connection string from app.config
string str = ConfigurationManager.ConnectionStrings["Bank"].ConnectionString;
SqlConnection con = new SqlConnection(str);

my app.config file is
<configuration>

<connectionStrings>

<add name="Bank"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\BankManagement(2)\BankManagement\bin\Debug\BankManagement.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />


</connectionStrings>


</configuration>

bt i am getting compilation error:

Error 1 A field initializer cannot reference the non-static field, method, or property

3
Contributors
2
Replies
12 Hours
Discussion Span
1 Year Ago
Last Updated
3
Views
abhinav1986
Newbie Poster
4 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Read about Compiler Error CS0236. If str and con are both instance fields of a class, you can't use str to initialize con like that.

gusano79
Practically a Master Poster
666 posts since May 2004
Reputation Points: 193
Solved Threads: 107
Skill Endorsements: 6

Make your "str" variable as static.

static string str = ConfigurationManager.ConnectionStrings["Bank"].ConnectionString;
SqlConnection con = new SqlConnection(str);
Mitja Bonca
Posting Maven
2,561 posts since May 2009
Reputation Points: 642
Solved Threads: 486
Skill Endorsements: 13

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0575 seconds using 2.65MB