Search code examples
c#ado.netsqlconnection

Must declare the scalar variable "@GenName"


I am getting this error when trying to run the code below. Any insight on to what I am doing wrong? I am pretty new to this, and want to get this to work pretty bad. I have gotten zero help from this site so far in a previous question I asked. But decided to give this forum another shot, before giving up on stackoverflow

protected void SaveButton_Click(object sender, EventArgs e)
{
    SqlConnection myConnection =
    new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
    SqlCommand myCommand = new SqlCommand(
    "INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
    "VALUES (@GenName, @GenAdd, @GenCity, @GenState, @GenZip, @GenPhone, @GenContact, @GenEPAID), myConnection");
    myCommand.Parameters.AddWithValue("@GeneratorName", GenName.Text);
    myCommand.Parameters.AddWithValue("@GeneratorAddress", GenAdd.Text);
    myCommand.Parameters.AddWithValue("@GeneratorCity", GenCity.Text);
    myCommand.Parameters.AddWithValue("@GeneratorState", GenState.Text);
    myCommand.Parameters.AddWithValue("@GeneratorZip", GenZip.Text);
    myCommand.Parameters.AddWithValue("@GeneratorPhone", GenPhone.Text);
    myCommand.Parameters.AddWithValue("@GeneratorContact", GenContact.Text);
    myCommand.Parameters.AddWithValue("@GeneratorEPAID", GenEPAID.Text);            

    myConnection.Open();
    myCommand.Connection = myConnection;
    myCommand.ExecuteNonQuery();
    myConnection.Close();
}

Solution

  • First, Stackoverflow is very helpful :) Don't give up on this platform.

    Now for your question:

    The parameters your SQL statement is expecting are:

    (@GenName, @GenAdd, @GenCity, @GenState, @GenZip, @GenPhone, @GenContact, @GenEPAID)
    

    While you later assign them with different names.

    It should be:

        myCommand.Parameters.AddWithValue("@GenName", GenName.Text);
        myCommand.Parameters.AddWithValue("@GenAdd", GenAdd.Text);
        myCommand.Parameters.AddWithValue("@GenCity", GenCity.Text);
        myCommand.Parameters.AddWithValue("@GenState", GenState.Text);
        myCommand.Parameters.AddWithValue("@GenZip", GenZip.Text);
        myCommand.Parameters.AddWithValue("@GenPhone", GenPhone.Text);
        myCommand.Parameters.AddWithValue("@GenContact", GenContact.Text);
        myCommand.Parameters.AddWithValue("@GenEPAID", GenEPAID.Text);
    

    When using @parameter , you must assign a value to a parameter with the same exact name.