Must Declare the Scalar Variable error

  • Thread starter Thread starter Oded Dror
  • Start date Start date
O

Oded Dror

Hi there,

Please take a look at the source code and tell me whats wrong?

Imports System.Data
Imports System.Data.SqlClient
Partial Class Test
Inherits System.Web.UI.Page
Const conString As String = "Data Source=.;Initial
Catalog=Northwind;Integrated Security=True"
Public Function MyInsertMethod() As Integer
Dim con As New SqlConnection(conString)
Dim insertString As String = "Exec usp_InsertTest
@CustomerID,@FirstName,@LastName"
Dim cmd As New SqlCommand(insertString, con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Function
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
Call MyInsertMethod()
End Sub
End Class

I created a table Test with CustomerID nvarchar(50),FirstName
nchar(10),@LastName nchar(10)

Along with the usp_InsertTest

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_InsertTest]
(@CustomerID nvarchar(50),@FirstName nchar(10),@LastName nchar(10))
AS
Insert into dbo.Test
(CustomerID,FirstName,LastName)
Values
(@CustomerID,@FirstName,@LastName)
Return

When I click submit I'm getting an error that says
"Must Declare the Scalar Variable"

Ho can I fix this

Thanks
Oded Dror
 
Hi,
If your SqlCommand object (cmd in this case) has some parameter in its
CommandText then you have to add those parameters to your SqlCommand
object's Parameters collection that is (something like):
cmd.Parameters.Add("@CustomerID", "SomeCustID")
cmd.Parameters.Add("@FirstName", "John")
cmd.Parameters.Add("@LastName", "DOE")

Check MSDN on SqlParameter for more information.
Regards.
 
I chenged the connection string to sqlDatasource1
This is sql client connection that I created
And now this is the error message that I'm getting
Format of the initialization string does not conform to specification
starting at index 0

How to fix that!

Thanks,
Oded Dror
 
Back
Top