连接属性中的对象引用为空 [英] Object Reference Null in Connection Property

查看:63
本文介绍了连接属性中的对象引用为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误是在这行

con.Open();



错误是: - 无法打开连接:System.NullReferenceException:Object参考不是

设置为一个对象的实例。



其他形式的问题不是这个代码中唯一的问题... < br $> b $ b


Error is :- Cannot open Connection:System.NullReferenceException:Object Reference Not
set to an instance of an object.

its not problem in other form its only prroblem in this code...

try
{
    con.Open();
    str = "select *from DatabaseLogin where user_id='" + textBox2.Text + "'";
    com = new OleDbCommand(str, con);
    OleDbDataReader reader = com.ExecuteReader();
    while (reader.Read())
    {
        checkedListBox1.Items.Add(reader["stckdemge"]);
    }
}
catch (Exception ex)
{
    MessageBox.Show(" " + ex);
}

推荐答案

错误信息非常清楚:

The error message is pretty clear:
Object Reference Not set to an instance of an object.



因为它出现在一行这么简单:


Since it occurs on a line as simple as this:

con.Open();

它只能是一件事:变量 con 已被声明,但是你没有给它赋值 - 因此,它是 null



在此代码之前的某个时刻,你需要执行类似的事情:

it can only be one thing: the variable con has been declared, but you have not assigned a value to it - hence, it is null

At some point before this code, you need to execute something like:

con = new OleDbConnection(strConnect);


你把cn作为连接对象

并使用con,它将如何运作。



你应该写..



OleDbConnection con;

public ExpireProduct(){InitializeComponent();

con = new OleDbConnection(@Provider = Microsoft.ACE.OLEDB.12.0; Data Source = D:\ MIS SYSTEM\AniPharmic\AniPharmic\MedicalDb.accdb; Jet OLEDB:Database密码=); }



you had made "cn" as connection object
and you use "con", how would it works.

You should write..

OleDbConnection con;
public ExpireProduct() { InitializeComponent();
con= new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\MIS SYSTEM\AniPharmic\AniPharmic\MedicalDb.accdb;Jet OLEDB:Database Password="); }

try
           {
               con.Open();
               str = "select *from DatabaseLogin where user_id='" + textBox2.Text + "'";
               com = new OleDbCommand(str, con);
               OleDbDataReader reader = com.ExecuteReader();
               while (reader.Read())
               {
                   checkedListBox1.Items.Add(reader["stckdemge"]);
               }
con.Close();
           }
           catch (Exception ex)
           {
               MessageBox.Show(" " + ex);
           }


这篇关于连接属性中的对象引用为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆