System.NullReferenceException Error while storing data in Access database
I am making a simple project where I take "id" and "name" from user and store it into the Access Data base. Whenever I press the Store button System.NullReferenceException Error Comes out. Here is the Code
Where I declared Oledpconnection.
public OleDbConnection Con;
public Form1()
{
InitializeComponent();
string connetionString = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/Mujahid/Documents/Visual Studio 2008/Projects/ts/ts/ts.accdb";
OleDbConnection Con = null;
Con = new OleDbConnection(connetionString);
try
{
Con.Open();
MessageBox.Show("Connection Open ! ");
开发者_C百科 Con.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
}
}
And here is the insert button programing
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText="insert into ts(ID,Name)" +"Values ('"+textBox1.Text+"','"+textBox2.Text+"')" ;
cmd.Connection= Con;
Con.Open();
cmd.ExecuteNonQuery();
Con.Close();
please Help !!
Con needs to be a form scope object, not redeclare in the forms constructor.
public OleDbConnection Con;
public Form1()
{
InitializeComponent();
string connetionString = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/Users/Mujahid/Documents/Visual Studio 2008/Projects/ts/ts/ts.accdb";
Con = new OleDbConnection(connetionString);
try
{
Con.Open();
MessageBox.Show("Connection Open ! ");
Con.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
}
}
public OleDbConnection Con;
...
OleDbConnection Con = null;
You never initialize the class scoped connection instance.
精彩评论