简体   繁体   中英

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 ! ");
            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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM