title: ASP.Net C# - Setting a MySQL query and parameters based on a condition
body: <p>How do I go about setting a MySQL query and parameters based on a condition?</p>
  
  <p>I want different queries based on 'questionSource' as shown below.</p>
  
  <p>However, in my code below, 'cmd' does not exist in the current context.</p>
  
  <p>Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.</p>
  
  <pre><code>//validation checks
  else
  {
      string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
      MySqlConnection conn = new MySqlConnection(connStr);
  
      string questionSource = Session["QuestionSource"].ToString();
      string cmdText = "";
  
      if (questionSource.Equals("S"))
      {
          cmdText += @"SELECT COUNT(*) FROM questions Q
                      JOIN users U
                      ON Q.author_id=U.user_id
                      WHERE approved='Y'
                      AND role=1
                      AND module_id=@ModuleID";
  
          MySqlCommand cmd = new MySqlCommand(cmdText, conn);
          cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
          cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
      }
      else if (questionSource.Equals("U"))
      {
          cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=@ModuleID AND author_id=@AuthorID;";
  
          MySqlCommand cmd = new MySqlCommand(cmdText, conn);
          cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
          cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
          cmd.Parameters.Add("@AuthorID", MySqlDbType.Int32);
          cmd.Parameters["@AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
      }
  
      int noOfQuestionsAvailable = 0;
      int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
  
      try
      {
          conn.Open();
  
          noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
  
          if (noOfQuestionsAvailable &lt; noOfQuestionsWanted)
          {
              lblError.Text = "There are not enough questions available to create a test.";
          }
          else
          {
              Session["TestName"] = txtName.Text;
              Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
              Session["QuestionSource"] = rblQuestionSource.SelectedValue;
              Session["TestModuleID"] = ddlModules.SelectedValue;
              Response.Redirect("~/create_test_b.aspx");
          }
      }
      catch
      {
          lblError.Text = "Database connection error - failed to get module details.";
      }
      finally
      {
          conn.Close();
      }
  }
  </code></pre>