我正在创建一个简单的项目,我从用户那里获取“id”和“name”并将其存储到Access Data库中。每当我按Store按钮System.NullReferenceException错误就出来了。这是代码
我宣布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 ! ");
}
}
这是插入按钮编程
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();
请帮助!!
答案 0 :(得分:3)
Con需要是表单范围对象,而不是表单构造函数中的重新声明。
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 ! ");
}
}
答案 1 :(得分:1)
public OleDbConnection Con;
...
OleDbConnection Con = null;
您永远不会初始化类作用域连接实例。