Domanda

I'm using C# and trying to insert a row into a SQL table. I have the following code.

    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;
    }

My problem occurs with this line:

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

For whatever reason, I'm getting this:

System.NullReferenceException: Object reference not set to an instance of an object.

I can't for the life of me figure out why, since I've checked, and I know spaceObjectName isn't null. Can anybody tell me where I'm going wrong? Any hints would be much appreciated! Thanks in advance!

È stato utile?

Soluzione

In your snippet, adsJarvis.InsertParameters["spaceObjectName"] is of course null because the compiler is looking for paramater named spaceObjectName, that's why it throws a NullReferenceException. You need to reference that in your aspx page.

Try this:

<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>

so in your code behind you can:

adsJarvis.InsertParameters["spaceObjectName"].DefaultValue = ...;
....
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top