2014-04-22 35 views
0

我正在使用C#並嘗試向SQL表中插入一行。我有以下代碼。這條線出現C#System.NullReferenceException即使初始化

string spaceObjectName, RA, DEC; 
    spaceObjectName = txtSpaceObject.Text; 
    RA = txtRA.Text; 
    DEC = txtDec.Text; 

    adsJarvis.InsertParameters["spaceObjectName"].DefaultValue = txtSpaceObject.Text; 
    adsJarvis.InsertParameters["RA"].DefaultValue = RA; 
    adsJarvis.InsertParameters["DEC"].DefaultValue = DEC; 

    try 
    { 
     adsJarvis.Insert(); 
     txtSpaceObject.Text = ""; 
     txtRA.Text = ""; 
     txtDec.Text = ""; 
    } 
    catch(Exception ex) 
    { 
     lblStatus.Text = "A database error has occurred. Message: " + ex.Message; 
    } 

我的問題:

adsJarvis.InsertParameters["spaceObjectName"].DefaultValue = txtSpaceObject.Text; 

無論出於何種原因,我得到這個:

System.NullReferenceException:未設置爲一個實例對象引用目的。

我不能爲我的生活弄清楚爲什麼,因爲我檢查了,而且我知道spaceObjectName不是null。 有人可以告訴我我要去哪裏嗎?任何提示將不勝感激!提前致謝!

+2

,什麼類型是它

試試這個? – attila

+0

@attila在.aspx文件中。 的 senschen

+0

根據您聲稱的問題,任何'adsJarvis','adsJarvis.InsertParameters [」spaceObjectName「]或'txtSpaceObject'爲null在運行時會引發異常,至少其中一個*是* null。 –

回答

0

在你的代碼片段中,adsJarvis.InsertParameters["spaceObjectName"]當然是null,因爲編譯器正在尋找名爲spaceObjectName的參數,這就是它拋出NullReferenceException的原因。你需要在你的aspx頁面中引用它。在你的代碼

<asp:AccessDataSource ID="adsJarvis" runat="server" DataFile="~/App_Code/adbJarvisStars.accdb" 
    SelectCommand="SELECT * FROM [spaceObjectTable]" 
    InsertCommand="INSERT INTO spaceObjectTable(spaceObjectName, RA, DEC) VALUES (?, ?, ?)"> 
     <InsertParameters> 
      <asp:Parameter Name="spaceObjectName" Type="string" /> 
      <asp:Parameter Name="RA" Type="string" /> 
      <asp:Parameter Name="DEC" Type="string" /> 
     </InsertParameters> 
</asp:AccessDataSource> 

這樣後面你可以:你在哪裏實例adsJarvis

adsJarvis.InsertParameters["spaceObjectName"].DefaultValue = ...; 
....