Search code examples
vb.netado.netsqlcommandsqlparameter

Why am I getting an error with my parameterized ADO query?


Dim txtFName As TextBox = CType(Wizard1.FindControl("txtFName"), TextBox)
Dim txtLName As TextBox = CType(Wizard1.FindControl("txtLName"), TextBox)

Dim MyDbConnection As New SqlConnection(ConfigurationManager.ConnectionStrings.Item("Journeyeast Connection String").ToString)
MyDbConnection.Open()

Dim SQL = "INSERT INTO Registration(FName, LName) VALUES (@FName, @LName)"

Dim MySqlCommand As New SqlCommand(SQL, MyDbConnection)
MySqlCommand.Parameters.Add("@FName", SqlDbType.NChar, 10, txtFName.Text)
MySqlCommand.Parameters.Add("@LName", SqlDbType.NChar, 10, txtLName.Text)

MySqlCommand.ExecuteNonQuery()

I am getting the following error:

The parameterized query '(@FName nchar(10),@LName nchar(10))INSERT INTO Registration(FNam' expects the parameter '@FName', which was not supplied.

What am I doing wrong?

BTW, I know nchar(10) is not a good choice for first and last name.


Solution

  • Because you haven't supplied parameter values.

    Take a look at:

    Dim SQL = "INSERT INTO Registration(FName, LName) VALUES (@FName, @LName)"
    
    Dim MySqlCommand As New SqlCommand(SQL, MyDbConnection)
    MySqlCommand.Parameters.AddWithValue("@FName",txtFName.Text)
    MySqlCommand.Parameters.AddWithValue("@LName",txtLName.Text)
    
    MySqlCommand.ExecuteNonQuery()
    

    EDIT:

    MySqlCommand.Parameters.Add("@FName", SqlDbType.NChar, 10).Value = txtFname.Text
    MySqlCommand.Parameters.Add("@LName", SqlDbType.NChar, 10).Value = txtFname.Text