ERROR system.nullreferenceexception对象引用未设置为对象的实例 [英] ERROR system.nullreferenceexception object reference not set to an instance of an object

查看:73
本文介绍了ERROR system.nullreferenceexception对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码 

Here's my code 

 private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                cmd.Connection = con;
                string sql = "select Department from test";
                cmd.CommandText = sql;

                OleDbDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    comboBox1.Items.Add(reader[0].ToString());
                }

                con.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error " + ex);
            }
        }

问题发生在上面加下划线的行

the problem occurs at the line that is underlined above

并显示此消息 

and this message appears 

system.nullreferenceexception对象引用未设置为对象的实例

system.nullreferenceexception object reference not set to an instance of an object

推荐答案

您需要实例化命令对象(无论您是否使用using语句都无关紧要)

You need to instantiate the command object (doesn't matter if you are using a using statement or not)

public void SelectDemo()
{
    using (OleDbConnection cn = new OleDbConnection("TODO"))
    {
        using (OleDbCommand cmd = new OleDbCommand())
        {
            cmd.Connection = cn;
            cmd.CommandText = "SELECT statement goes here";
            cn.Open();
            // ...
        }
    }
}


以上是OleDb,与SqlClient相同。

The above is OleDb, same for SqlClient.


这篇关于ERROR system.nullreferenceexception对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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