Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Im trying to execute the following:

 

mySqlCmd.Parameters.Add("@Parent_ID", SqlDbType.Int).Value = (sectionUpdate.iSection.ParentID == 0 ? DBNull.Value : myParentID);

 

However i get an error that Null cant be converted to Int. Is there any way i can uyse the SqlParameters approach but pass in a Null value for the field or must i wrap the entire connection within a IF/ELSE statement one containing a hard-coded NULL within the query and the other as a standard parameter with a proper int value?

 

 

Thanks

Posted

Me.SqlCommand1.Parameters(1).Value = DBNull.Value

 

I use VB but in this case it doesn't matter. The type of Parameters(1) is SqlDbType.Int. I didn't experience the same error you have. Are you sure it's your code that is wrong? Have you setup your database correctly? Maybe your source column doesn't allow null. Just guessing though.

 

Here's a complete list of my (sample) code:

        Try
           Me.SqlConnection1.Open()
           Me.SqlCommand1.Parameters(0).Value = "23"
           Me.SqlCommand1.Parameters(1).Value = DBNull.Value
           Me.SqlCommand1.ExecuteNonQuery()
       Catch exc As Exception
           Me.SqlConnection1.Close()
       Finally
           Me.SqlConnection1.Close()
       End Try

Amir Syafrudin
  • *Experts*
Posted (edited)

My guess the problem was with the casting. The ternary can't resolve the left side (DBNull.Value, which is just "object") and the right side (an int). You'd normally have to cast the int as an object, to match the type of DBNull.Value.

 

On a side note, if quantass is reading this, why would you pass myParentID when you're checking sectionUpdate.iSection.ParentID? Normally the tertiary operator is used just like you have it, but returns the value it's comparing. For example:

Change
... = (sectionUpdate.iSection.ParentID == 0 ? DBNull.Value : myParentID); 
to this:
... = (sectionUpdate.iSection.ParentID == 0 ? DBNull.Value : sectionUpdate.iSection.ParentID); 

 

-ner

Edited by Nerseus
"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...