如何避免Object引用未设置为实例错误? [英] How to avoid the Object reference not set to an instance error?

查看:94
本文介绍了如何避免Object引用未设置为实例错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何避免Object引用未设置为实例错误?我只在设置和部署后才收到此错误。它在visual studio环境中的调试和发布模式下工作正常吗?最初,控件从getproject()函数开始。然后,它调用属性obOpenedSqlConnection。





How to avoid the Object reference not set to an instance error? I am getting this error only after setup and deployment. It works fine in debug and release mode inside the visual studio environment? Initially the control starts from getproject() function. Then, it calls the property obOpenedSqlConnection.


public class OutlookDataAccess
    {

        #region Public Methods and Properties
        SqlConnection _sqlConnection; //= new SqlConnection(); // null;
        SqlCommand obSqlCommand;
        SqlDataAdapter obSqlDataAdapter;

        SqlParameter parm;

        //SqlConnection _sqlConnection = new SqlConnection();

        public SqlConnection obOpenedSqlConnection
        {
            get
            {
                MessageBox.Show("Before Open");
                if (_sqlConnection != null)
                {
                    MessageBox.Show("inside Open");
                    if (_sqlConnection.State == ConnectionState.Closed)
                    {
                        try
                        {
                            MessageBox.Show( "Before Open");
                           _sqlConnection.Open();                         
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Open Exception");
                            throw ex;
                        }
                    }
                    return _sqlConnection;
                }
                else
                { 
                    var connectionString = ConfigurationManager.ConnectionStrings["OutlookConnectionStringLocal"].ConnectionString;
                    
                    MessageBox.Show("Before Connection creation");
                    _sqlConnection = new SqlConnection(connectionString);
                    MessageBox.Show("After Connection creation");
                    return _sqlConnection;  
                }
            }
        }

        private void CloseSqlConnection()
        {
            if (_sqlConnection != null)
            {
                if (_sqlConnection.State == ConnectionState.Open)
                    _sqlConnection.Close();
            }
        }

        private void ClearCommandParameters()
        {
            if (obSqlCommand != null)
            {
                obSqlCommand.Parameters.Clear();
            }
        }

        private DataTable GetOutputDataTable(SqlDataAdapter sqlDataAdapter)
        {
            DataTable dataTable = new DataTable();
            if (sqlDataAdapter != null)
            {
                sqlDataAdapter.Fill(dataTable);
                ClearCommandParameters();
            }
            return dataTable;
        }

        public DataTable GetProject(string emailId)
        {
            try
            {
                MessageBox.Show("inside get project");
               
                obSqlCommand = new SqlCommand("sp_GetClientContact", obOpenedSqlConnection);
                //MessageBox.Show(emailId, "getprojectid");
                obSqlCommand.CommandType = CommandType.StoredProcedure;
                obSqlCommand.Parameters.AddWithValue("@emailId", emailId);
                obSqlDataAdapter = new SqlDataAdapter(obSqlCommand);


            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString(), "invalid object");
                throw exp;

            }
            finally
            {
                CloseSqlConnection();

            }
            return GetOutputDataTable(obSqlDataAdapter);
        }
}

推荐答案

我猜你的问题是
var connectionString = ConfigurationManager.ConnectionStrings["OutlookConnectionStringLocal"].ConnectionString;

返回null,因为您的实时配置可能与您调试一个不同。





就个人而言,我会为每个呼叫创建一个连接,并在呼叫结束时将其用于垃圾收集,尽管有理由不这样做。您的班级IMO还有一些其他问题:



1.

is returning null as your live config probably differs from you debug one.


Personally I'd create a connection for each call and put it up for Garbage collection at the end of the call, though there are reasons for not doing this. There are a few other thing wrong with your class IMO:

1.

obOpenedSqlConnection

应该是一种方法。

2.不要抓住生活中的例外。

3.在你修改你的commant时,考虑一个使用语句,这将自动关闭你的连接,但也可以处理它。

4.考虑以下方法:创建连接,创建一个新的命令对象并填充其参数(clearig感觉很脆弱)。 />
5.在

Should be a method.
2. Don't catch the gerneic exception.
3. Consider a using statement when you istantiate your commant, this will auto-close your connection, but may also dispose it.
4. Consider methods to: Create the connection, Create a new command object and fill its parameters (the clearig feels brittle).
5. Creating the DataAdapter in the

GetOutputDataTable

中创建DataAdapter以缩小其范围。

reducing its scope.


使用new关键字<创建_sqlConnection的对象br />
create object of _sqlConnection using new keyword
SqlConnection _sqlConnection = new SqlConnection();


避免此错误的最佳方法是,始终创建要使用的对象或类的新实例。有时候我们会忘记这个小点而没有初始化和创建我们用来使用它的对象的实例。这就是为什么会出现这种异常的原因。


在您的条件下检查您使用空对象分配值的编码。仔细跟踪代码。



--Amit
The best way to avoid this error is, always create a new instance of the objects or classes which you are going to use. Sometimes we use to forget this little point and without initializing and creating instance of the object we use to use this. That's why this kind of exception comes.

In your condition check for the coding where you are using null objects to assign values. Trace the code carefully.

--Amit


这篇关于如何避免Object引用未设置为实例错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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