Emad-ud-deen
Emad-ud-deen

Reputation: 4864

Error converting nvarchar to numeric

I used the following statement for a parameter.

.Parameters("@SearchValue").Value = TextBoxParentID.Text

for this query:

 objSqlCommand.CommandText = "Select ID " & _
                               "From Parents " & _
                              "Where ID = @SearchValue"

ID is a SQL server numeric column but I get this error:

error converting nvarchar to numeric

Can you show me the coding needed fix this?

Upvotes: 2

Views: 1961

Answers (1)

Oybek
Oybek

Reputation: 7243

At this point you are trying to assign value which is of type string and the parameter is bound as string (nvarchar). You need to convert it at first.

    ' Let's suppose that this is a value from your textbox
    Dim strNumber As String = "12"

    ' Prepare a placeholder to convert your string value into integer
    Dim myInteger As Integer

    ' Try to convert
    If Int32.TryParse(strNumber, myInteger) Then
        'If the conversion is successful

        Dim myConnection As New SqlConnection("Your ConnectionString")
        Dim myCommand As New SqlCommand("INSERT INTO Foo(Bar) VALUES (@Bar", myConnection)

        'Use this syntax to assign values to parameters
        myCommand.Parameters.AddWithValue("Bar", myInteger)
    End If

This snippet also uses AddWithValue method. I suggest you to use this approach.

Upvotes: 1

Related Questions