title: Must declare the scalar variable "@UserName"
body: <p>I keep getting an error that I don't understand.</p>
  <blockquote>
  <p>Must declare the scalar variable &quot;@varname&quot;</p>
  </blockquote>
  <p>My aim is to create a login page that uses 2 textboxes and a button, where it checks if the user exits based on the information stored in a SQL database.</p>
  <p>This is where I think the problem is coming from:</p>
  <pre><code>private bool DBConnection(string userName, string password)
  {
      SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;ConnectionString&quot;].ConnectionString);
      
      //string cmdString = (&quot;SELECT UserName, Password FROM Users WHERE UserName ='&quot; + userName +
      //                    &quot;'AND Password ='&quot; + password + &quot;'&quot;);         //REMOVED AS THIS IS PRONE TO SQL INJECTIONS
      
      string cmdString = (&quot;SELECT * FROM Users WHERE UserName = @uname AND Password = @pw&quot;);
      
      SqlCommand cmd = new SqlCommand(cmdString, conn);
      
      cmd.Parameters.Add(&quot;uname&quot;, SqlDbType.VarChar).Value = userName;
      cmd.Parameters.Add(&quot;pw&quot;, SqlDbType.VarChar).Value = password;
  
      DataSet loginCredentials = new DataSet();
      SqlDataAdapter dataAdapter;
  
      try
      {
          if (conn.State.Equals(ConnectionState.Closed))
          {
              conn.Open();
  
              dataAdapter = new SqlDataAdapter(cmdString, conn);
              dataAdapter.Fill(loginCredentials);
  
              conn.Close();
  
              if (loginCredentials != null)
              {
                  if (loginCredentials.Tables[0].Rows.Count &gt; 0)
                  {
                      return true;
                  }
                  else
                  {
                      lblMessage.Text = &quot;Incorrect Username or Password&quot;;
                      lblMessage.Visible = true;
                  }
              }   
          }
      }
      catch (Exception err)
      {
          lblMessage.Text = err.Message.ToString() + &quot; Error connecting to the Database // &quot; + cmd.Parameters.Count;
          lblMessage.Visible = true;
          return false;
      }
  
      return false;
  }
  </code></pre>
  <p>specifically where <code>dataAdapter.Fill(loginCredentials);</code> is being executed.</p>
  <p>The commented-out statement works successfully in logging in a user with the correct username and password, but as far as I know is not secure, as it's vulnerable to SQL injections and this is why I'm trying to parameterize the SQL statement.</p>
  <p>error screenshot below:
  <a href="https://i.stack.imgur.com/w0VG8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w0VG8.png" alt="Error screenshot" /></a></p>