对象引用未设置为对象的实例SQL DataTable

时间:2018-02-14 06:42:41

标签: c# asp.net linq-to-sql

我有一个getDataTable函数,用于从后面的ASP.NET Web窗体代码查询我的数据库。在我的相关question中,我查询所有已结算的研究,其输出为StudyIDStudyName。此查询附加到下拉列表数据源。但是,以下代码段中的System.NullReference会引发dtGeneric.Dispose()异常:

public static DataTable getDataTable(string sSQL, SqlConnection conn)
{
    DataTable dtGeneric = new DataTable();
    SqlCommand command = new SqlCommand();

    DataSet oDataSet = new DataSet();
    //create a new dataset...
    oDataSet.Clear();

    SqlDataAdapter objDataAdapter = new SqlDataAdapter(sSQL, conn);
    objDataAdapter.SelectCommand.CommandTimeout = 900;
    try
    {
        objDataAdapter.Fill(oDataSet, "Generic"); //fill dataSet with data...
        dtGeneric = oDataSet.Tables["Generic"];
        return dtGeneric;
    }
    catch (System.Exception e)
    {

        Debug.WriteLine(e.ToString());
        return null;
    }
    finally
    {
        dtGeneric.Dispose();
        objDataAdapter.Dispose();
        command.Dispose();
        conn.Close();
    }

    return dtGeneric;

}

更新:修改了以上内容,以便在方法结束时返回dtGeneric。但是,同样的错误仍然存​​在。堆栈跟踪如下:

[NullReferenceException: Object reference not set to an instance of an 
object.]
SharedFunctions.getDataTable(String sSQL, SqlConnection conn) in 
c:\inetpub\wwwroot\Prototyping\App_Code\SharedFunctions.cs:263
Reports.GetResponses(Int32 iStudyID) in 
c:\inetpub\wwwroot\Prototyping\Reports.aspx.cs:87
Reports.Page_Load(Object sender, EventArgs e) in 
c:\inetpub\wwwroot\Prototyping\Reports.aspx.cs:151
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.<LoadRecursiveAsync>d__246.MoveNext() +284
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31

1 个答案:

答案 0 :(得分:1)

按如下方式更改代码:

最后移动{ "key": "f8", "command": "macros.PowershellRunSelection", "when": "editorTextFocus && editorLangId == 'powershell'" }, { "key": "f5", "command": "macros.PowershellRun", "when": "editorTextFocus && editorLangId == 'powershell'" }

return