简体   繁体   中英

Object reference not set to an instance of an object - error

I'm trying to insert in an Access Database, from visual C#. But i got this error: error

What am I doing wrong in code? The values are correct, they comes from the input boxes.

Thanks!

From the picture it looks like the adapter.InsertCommand property is null.
Instead of

adapter.Insertcommand.CommandText = ...

use

insertCommand.CommandText = ...
adapter.InsertCommand = insertCommand;

You're creating the OleDbDataAdapter adapter ok, and you're creating a (stand-alone) OleDbCommand insertCommand as well - but you're NOT creating an instance for adapter.InsertCommand - that variable will be NULL !

You need to do:

OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.InsertCommand = new OleDbCommand();

Create the adapter.InsertCommand instead of a stand-alone instance.

At bottom left of picture I see "adapter.InserCommand" is null while the error occurred after you created a new "oleDbCommand" and it's the source of exception. Why ? Because you created one "oleDbCommand" and didn't assign it to your adapter.

Anyway, the way you deal with sql is not recommended and the code is prone to sql injection attacks. Also putting a large amount of code inside a "Try" block is not recommended since you cannot find the source of problem later.

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