2015-11-17 28 views
0

爲什麼我拋不指定對象裁判錯誤的在這條線的實例對象:CMD.Connection關聯問題 - 對象錯誤

CMD.Connection = connection; 

對於此代碼:

public static int EstablishDBConnection(String strCommandText, SqlConnection connection, DataTable DT = null, String[,] aryParameters = null, SqlDbType[] oAryType = null, bool DoesReturnData = true, int intTimeout = 3600, int intCommandType = 4) 
{ 
    SqlCommand CMD = null; 
    SqlDataAdapter DA = null; 
    int intUbound = 0; //stores max ary size 
    int returnVal = 0; 

    try 
    { 
     //Set up our connection 
     CMD.Connection = connection; 

我在.net解決方案中有這個工作,但在我的ASP.NET項目中,它觸發了這個錯誤。我通過這個呼叫者:

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Reports"].ConnectionString); 
Library.Utility.DB.Connection.EstablishDBConnection("usp_get_toolsweb_securitylvl",connection , dtSecurity, aryParameters, oAryType); 

這是我的連接字符串:

<connectionStrings> 
    <add name="Reports" connectionString="Server=someserver\dev;uid=username;pwd=password;Database=Reports" providerName="System.Data.SqlClient" /> 
</connectionStrings> 

我證實了我的連接字符串正確傳遞和傳入的參數填充即時窗口。

回答

1

您需要在使用它之前創建一個SqlCommand實例。

即。改變

SqlCommand CMD = null; 

SqlCommand CMD = new SqlCommand(); 
1

您應該創建的SqlCommand一個新實例,並將其分配給變量CMD設置CMD.Connection前:

SqlCommand CMD = new SqlCommand(); 

然後:

CMD.Connection = connection; 

SqlCommand CMD = null;僅將空值分配給參考CMD