在 Access 数据库中存储数据时出现 System.NullReferenceException 错误
我正在制作一个简单的项目,其中我从用户那里获取“id”和“name”并将其存储到 Access 数据库中。每当我按下“存储”按钮时,就会出现 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();
请帮助!
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 !!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Con 需要是表单范围对象,而不是在表单构造函数中重新声明。
Con needs to be a form scope object, not redeclare in the forms constructor.
...
您永远不会初始化类范围的连接实例。
...
You never initialize the class scoped connection instance.