I have started today to learn about the SQL connection in C# programming. And I tried some basic thing like the Insert, Delete etc.
And I wanted to try the same thing in another project but I have a problem. Because It shows me an error that I can’t solve 🙁
Error:
A field initializer cannot reference the non-static field, method, or property ‘Artikujt.Form1.con’.
Here is my code (I just started to connect it with the Database in SQL)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Artikujt
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(@"Data Source=TALY-PC;Initial Catalog=Katalogi;Integrated Security=True;Pooling=False");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
DataSet dsl = new DataSet();
public Form1()
{
InitializeComponent();
}
}
}
The error is in this code at the variable con
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblArtikujt", con);
I created the Database in SQL (in Visual Studio)… I also added the Data Source. I did the exact thing that I did before…. but it isn’t working 🙁
The error is exactly what it says. You cannot use
conin your initialization ofdabecause it will only be created during an instance creation. You will need to createconasstaticor put your initialization lines in your constructor.HOWEVER, you should probably not do this in practice as you are just asking for somebody to open a
SqlConnectionand leave it open. You should probably fall more into the practice of creating your connections using ausingblock to take advantage of the disposing patternStatic:
Or instantiation in the constructor:
I will let you research the using block yourself