Executenonquery return value

mick picture mick · Apr 12, 2011 · Viewed 7.3k times · Source

I want to perform a search on a table to see if record exists. I do not want to perform insert or update after. I have done this already but somehow I cannot get this to work. On my asp.net page I cannot seem to get any value returned. The error is "input string not in correct format" I ma sure it is obvious but I cannot seem to see it now!

here is my code:

Dim con As New SqlConnection("connstring")
Dim cmd As New SqlCommand("checkname", con)
cmd.CommandType = CommandType.StoredProcedure

cmd.Parameters.Add(New SqlParameter("@d", SqlDbType.Int))
cmd.Parameters("@id").Value = TextBox1.Text

Dim para As New SqlParameter
para.Direction = ParameterDirection.ReturnValue
para.ParameterName = "returnvalue"
cmd.Parameters.Add(para)

con.Open()


cmd.ExecuteNonQuery()
Dim exists As Integer
exists = Convert.ToInt32(cmd.Parameters("returnvalue").Value)
If exists = 1 Then
    Label1.Text = "You......"
         ElseIf exists = 0 Then
    Label1.Text = "You....."

End If
con.Close()

stored procedure:

CREATE PROCEDURE checkname 
    -- Add the parameters for the stored procedure here
    @id int
AS
  --This means it exists, return it to ASP and tell us
 -- SELECT 'already exists'

IF EXISTS(SELECT * FROM attendees WHERE id = @id)
BEGIN
RETURN 1
END
ELSE
BEGIN
   RETURN 0
END

Answer

Andrew Shepherd picture Andrew Shepherd · Apr 12, 2011

You need to ensure that you are passing an integer.

int intValue;
if(!int.TryParse(TextBox1.Text, out intValue))
{
     // Update your page to indicate an error

     return;

}

cmd.Parameters.Add(New SqlParameter("id", SqlDbType.Int));
cmd.Parameters("id").Value = intValue; 

(Technically you don't need the "@" character when defining the parameters in the .NET code.)