PDA

View Full Version : تو #C نمیشه متغیر عمومی واسه کانکشن تعریف کرد؟!



Developer Programmer
پنج شنبه 24 بهمن 1387, 19:14 عصر
عجیبه!
این کد در VB.NET درست کار میکنه


Dim myConnection As SqlConnection = New SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True")
Dim myCommand As SqlCommand = New SqlCommand("Select * from Employees", myConnection)


اما وقتی میخوام مشابه این رو در #C بنویسم:



namespace TestDB
{
public partial class Form1 : Form
{
SqlConnection mySqlConnection = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
SqlCommand mySqlCommand = new SqlCommand("select * from employees", mySqlConnection);
mySqlConnection رو نمیشناسه.

همینطور در مورد



SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

مشکل از کجاست؟

اوبالیت به بو
پنج شنبه 24 بهمن 1387, 19:43 عصر
به این دلیل که در #C کامپایلر نمی تونه یه Instance از جنس sqlConnection خارج از متد بسازه. بخونید:


Instance fields cannot be used to initialize other instance fields outside a method. If you are trying to initialize a variable outside a method, consider performing the initialization inside the class constructor. For more information, see Methods (C# Programming Guide) (http://msdn.microsoft.com/en-us/library/ms173114.aspx).

از این الگو استفاده کنید:

http://barnamenevis.org/forum/showpost.php?p=653476&postcount=22