Search code examples
c#.netsqlsqlcommandsqlparameter

Must declare the scalar variable “@Login”. Error when trying to add parameter to SqlDataSource


I have this error : Must declare the scalar variable "@Login".

My code :

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["intranetv2"].ConnectionString))
{

    SqlCommand cmd = new SqlCommand("insert into [MyBase].[Dbo].[LogErrors] (Username, StackTrace, ShortDescription, DetailDescription, ErrorType) VALUES (@Login, @Stack, @Message, @Txt, @Source)", conn);

                SqlParameter param = new SqlParameter();
                param.ParameterName = "Login";
                param.Value = user.Login;
                param.ParameterName = "Stack";
                param.Value = ex.StackTrace;
                param.ParameterName = "Message";
                param.Value = ex.Message;
                param.ParameterName = "Txt";
                param.Value = Txt;
                param.ParameterName = "Source";
                param.Value = ex.Source;
                // 3. add new parameter to command object
                cmd.Parameters.Add(param);
                conn.Open();
                return cmd.ExecuteNonQuery();
}

I have try with th e'@' in the param but i have the same error.


Solution

  • You must create a new SqlParameter for each Parameter, it should be like this:

    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["intranetv2"].ConnectionString))
    {
    
        SqlCommand cmd = new SqlCommand("insert into [MyBase].[Dbo].[LogErrors] (Username, StackTrace, ShortDescription, DetailDescription, ErrorType) VALUES (@Login, @Stack, @Message, @Txt, @Source)", conn);
    
                    SqlParameter param = new SqlParameter();
                    param.ParameterName = "@Login";
                    param.Value = user.Login;
                    cmd.Parameters.Add(param);
    
                    SqlParameter param2 = new SqlParameter();
                    param2.ParameterName = "@Stack";
                    param2.Value = ex.StackTrace;
                    cmd.Parameters.Add(param2);
        (...)