Compare input with data in database in c# forms










0














I am trying to create a quiz in c# using forms and a database. I am currently struggling with comparing the input into a textbox with the correct answer which is in the database.
For example: If I input 'A' in the textbox for the answer and the correct answer stored in the database was 'A' it would add one to the score.



The code I have used for this (which doesn't work) is below:



SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionID=3", con);
cmd.Parameters.AddWithValue("@Answer", InputAnswerTxt.Text);

con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
using (SqlDataReader re = cmd.ExecuteReader())

if (re.Read())

string AnswerSelection = (string)re["Answer"];
SetScore = SetScore++;


MessageBox.Show("Your score is : " + SetScore);


con.Close();


Any suggestions at all would be helpful! If you need to see some more of where the code is embedded please do let me know.










share|improve this question




























    0














    I am trying to create a quiz in c# using forms and a database. I am currently struggling with comparing the input into a textbox with the correct answer which is in the database.
    For example: If I input 'A' in the textbox for the answer and the correct answer stored in the database was 'A' it would add one to the score.



    The code I have used for this (which doesn't work) is below:



    SqlConnection con = new SqlConnection(conn);
    SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionID=3", con);
    cmd.Parameters.AddWithValue("@Answer", InputAnswerTxt.Text);

    con.Open();
    SqlDataAdapter adpt = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adpt.Fill(ds);
    using (SqlDataReader re = cmd.ExecuteReader())

    if (re.Read())

    string AnswerSelection = (string)re["Answer"];
    SetScore = SetScore++;


    MessageBox.Show("Your score is : " + SetScore);


    con.Close();


    Any suggestions at all would be helpful! If you need to see some more of where the code is embedded please do let me know.










    share|improve this question


























      0












      0








      0







      I am trying to create a quiz in c# using forms and a database. I am currently struggling with comparing the input into a textbox with the correct answer which is in the database.
      For example: If I input 'A' in the textbox for the answer and the correct answer stored in the database was 'A' it would add one to the score.



      The code I have used for this (which doesn't work) is below:



      SqlConnection con = new SqlConnection(conn);
      SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionID=3", con);
      cmd.Parameters.AddWithValue("@Answer", InputAnswerTxt.Text);

      con.Open();
      SqlDataAdapter adpt = new SqlDataAdapter(cmd);
      DataSet ds = new DataSet();
      adpt.Fill(ds);
      using (SqlDataReader re = cmd.ExecuteReader())

      if (re.Read())

      string AnswerSelection = (string)re["Answer"];
      SetScore = SetScore++;


      MessageBox.Show("Your score is : " + SetScore);


      con.Close();


      Any suggestions at all would be helpful! If you need to see some more of where the code is embedded please do let me know.










      share|improve this question















      I am trying to create a quiz in c# using forms and a database. I am currently struggling with comparing the input into a textbox with the correct answer which is in the database.
      For example: If I input 'A' in the textbox for the answer and the correct answer stored in the database was 'A' it would add one to the score.



      The code I have used for this (which doesn't work) is below:



      SqlConnection con = new SqlConnection(conn);
      SqlCommand cmd = new SqlCommand("select Answer from Questions where QuestionID=3", con);
      cmd.Parameters.AddWithValue("@Answer", InputAnswerTxt.Text);

      con.Open();
      SqlDataAdapter adpt = new SqlDataAdapter(cmd);
      DataSet ds = new DataSet();
      adpt.Fill(ds);
      using (SqlDataReader re = cmd.ExecuteReader())

      if (re.Read())

      string AnswerSelection = (string)re["Answer"];
      SetScore = SetScore++;


      MessageBox.Show("Your score is : " + SetScore);


      con.Close();


      Any suggestions at all would be helpful! If you need to see some more of where the code is embedded please do let me know.







      c# database forms






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 at 22:27









      CSharpRocks

      3,96411221




      3,96411221










      asked Nov 9 at 22:25









      tonique

      62




      62






















          2 Answers
          2






          active

          oldest

          votes


















          0














          If you can provide your database schema it might help. Since you have the user's answer in memory (not in DB) You might not need to attach it as a parameter to the SQL command. You should be able to just pull down the answer to the question your want (looks like where questionID=3) then compare InputAnswerTxt.Text with what the DB returns. Then count up your score if they are equal to each other.



          More of your code my need to be posted (IE where some of these variables are defined, and the DB schema, etc) to give further advice.






          share|improve this answer






























            0














            I am assuming the number of quiz questions you have are in 100s at best and not in 1000000+s. So, rather than going to the database every time you receive an answer, you should grab all the question Id and their correct answer right in the beginning and store it in a dictionary. Then check the dictionary for correctness and update the score.



            Below is a rough guideline, it's not an entirely working code, but that should give you a good enough idea, hopefully, else ask in the comment.



            So in your constructor, you could make a call to retrieve all the answers. Like below:



             private Dictionary<string, string> _correctAnswerLookup;
            public Form1()

            InitializeComponent();
            _correctAnswerLookup = GetCorrectAnswerByQuestionLookup();


            private Dictionary<string, string> GetCorrectAnswerByQuestionLookup()

            Dictionary<string, string> correctAnswerLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            using (SqlConnection connection = new SqlConnection(connectionString))

            SqlCommand cmd = new SqlCommand("select QuestionId, Answer from Questions", connection);
            try

            connection.Open();
            var reader = cmd.ExecuteReader();
            while (reader.Read())

            string questionId = (string)reader["QuestionId"];
            string answer = (string)reader["Answer"];
            if (!correctAnswerLookup.ContainsKey(questionId))

            correctAnswerLookup.Add(questionId, answer);



            catch (Exception e)

            // your exception handling


            return correctAnswerLookup;



            And on your answer received event, you could just check the lookup and update the score. Handle the subtleties about validation and null check etc yourself.



             private void OnAnswerSubmitted()

            string currentQuestionId = ""; // however you get this in your UI.
            string selectedAnswer = "";

            if (_correctAnswerLookup[currentQuestionId] == selectedAnswer)

            scoreCounter++;


            lblScoreCounter.Text = scoreCounter.ToString();






            share|improve this answer




















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234055%2fcompare-input-with-data-in-database-in-c-sharp-forms%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              If you can provide your database schema it might help. Since you have the user's answer in memory (not in DB) You might not need to attach it as a parameter to the SQL command. You should be able to just pull down the answer to the question your want (looks like where questionID=3) then compare InputAnswerTxt.Text with what the DB returns. Then count up your score if they are equal to each other.



              More of your code my need to be posted (IE where some of these variables are defined, and the DB schema, etc) to give further advice.






              share|improve this answer



























                0














                If you can provide your database schema it might help. Since you have the user's answer in memory (not in DB) You might not need to attach it as a parameter to the SQL command. You should be able to just pull down the answer to the question your want (looks like where questionID=3) then compare InputAnswerTxt.Text with what the DB returns. Then count up your score if they are equal to each other.



                More of your code my need to be posted (IE where some of these variables are defined, and the DB schema, etc) to give further advice.






                share|improve this answer

























                  0












                  0








                  0






                  If you can provide your database schema it might help. Since you have the user's answer in memory (not in DB) You might not need to attach it as a parameter to the SQL command. You should be able to just pull down the answer to the question your want (looks like where questionID=3) then compare InputAnswerTxt.Text with what the DB returns. Then count up your score if they are equal to each other.



                  More of your code my need to be posted (IE where some of these variables are defined, and the DB schema, etc) to give further advice.






                  share|improve this answer














                  If you can provide your database schema it might help. Since you have the user's answer in memory (not in DB) You might not need to attach it as a parameter to the SQL command. You should be able to just pull down the answer to the question your want (looks like where questionID=3) then compare InputAnswerTxt.Text with what the DB returns. Then count up your score if they are equal to each other.



                  More of your code my need to be posted (IE where some of these variables are defined, and the DB schema, etc) to give further advice.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 9 at 22:42

























                  answered Nov 9 at 22:34









                  DMarczak

                  1119




                  1119























                      0














                      I am assuming the number of quiz questions you have are in 100s at best and not in 1000000+s. So, rather than going to the database every time you receive an answer, you should grab all the question Id and their correct answer right in the beginning and store it in a dictionary. Then check the dictionary for correctness and update the score.



                      Below is a rough guideline, it's not an entirely working code, but that should give you a good enough idea, hopefully, else ask in the comment.



                      So in your constructor, you could make a call to retrieve all the answers. Like below:



                       private Dictionary<string, string> _correctAnswerLookup;
                      public Form1()

                      InitializeComponent();
                      _correctAnswerLookup = GetCorrectAnswerByQuestionLookup();


                      private Dictionary<string, string> GetCorrectAnswerByQuestionLookup()

                      Dictionary<string, string> correctAnswerLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                      using (SqlConnection connection = new SqlConnection(connectionString))

                      SqlCommand cmd = new SqlCommand("select QuestionId, Answer from Questions", connection);
                      try

                      connection.Open();
                      var reader = cmd.ExecuteReader();
                      while (reader.Read())

                      string questionId = (string)reader["QuestionId"];
                      string answer = (string)reader["Answer"];
                      if (!correctAnswerLookup.ContainsKey(questionId))

                      correctAnswerLookup.Add(questionId, answer);



                      catch (Exception e)

                      // your exception handling


                      return correctAnswerLookup;



                      And on your answer received event, you could just check the lookup and update the score. Handle the subtleties about validation and null check etc yourself.



                       private void OnAnswerSubmitted()

                      string currentQuestionId = ""; // however you get this in your UI.
                      string selectedAnswer = "";

                      if (_correctAnswerLookup[currentQuestionId] == selectedAnswer)

                      scoreCounter++;


                      lblScoreCounter.Text = scoreCounter.ToString();






                      share|improve this answer

























                        0














                        I am assuming the number of quiz questions you have are in 100s at best and not in 1000000+s. So, rather than going to the database every time you receive an answer, you should grab all the question Id and their correct answer right in the beginning and store it in a dictionary. Then check the dictionary for correctness and update the score.



                        Below is a rough guideline, it's not an entirely working code, but that should give you a good enough idea, hopefully, else ask in the comment.



                        So in your constructor, you could make a call to retrieve all the answers. Like below:



                         private Dictionary<string, string> _correctAnswerLookup;
                        public Form1()

                        InitializeComponent();
                        _correctAnswerLookup = GetCorrectAnswerByQuestionLookup();


                        private Dictionary<string, string> GetCorrectAnswerByQuestionLookup()

                        Dictionary<string, string> correctAnswerLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        using (SqlConnection connection = new SqlConnection(connectionString))

                        SqlCommand cmd = new SqlCommand("select QuestionId, Answer from Questions", connection);
                        try

                        connection.Open();
                        var reader = cmd.ExecuteReader();
                        while (reader.Read())

                        string questionId = (string)reader["QuestionId"];
                        string answer = (string)reader["Answer"];
                        if (!correctAnswerLookup.ContainsKey(questionId))

                        correctAnswerLookup.Add(questionId, answer);



                        catch (Exception e)

                        // your exception handling


                        return correctAnswerLookup;



                        And on your answer received event, you could just check the lookup and update the score. Handle the subtleties about validation and null check etc yourself.



                         private void OnAnswerSubmitted()

                        string currentQuestionId = ""; // however you get this in your UI.
                        string selectedAnswer = "";

                        if (_correctAnswerLookup[currentQuestionId] == selectedAnswer)

                        scoreCounter++;


                        lblScoreCounter.Text = scoreCounter.ToString();






                        share|improve this answer























                          0












                          0








                          0






                          I am assuming the number of quiz questions you have are in 100s at best and not in 1000000+s. So, rather than going to the database every time you receive an answer, you should grab all the question Id and their correct answer right in the beginning and store it in a dictionary. Then check the dictionary for correctness and update the score.



                          Below is a rough guideline, it's not an entirely working code, but that should give you a good enough idea, hopefully, else ask in the comment.



                          So in your constructor, you could make a call to retrieve all the answers. Like below:



                           private Dictionary<string, string> _correctAnswerLookup;
                          public Form1()

                          InitializeComponent();
                          _correctAnswerLookup = GetCorrectAnswerByQuestionLookup();


                          private Dictionary<string, string> GetCorrectAnswerByQuestionLookup()

                          Dictionary<string, string> correctAnswerLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                          using (SqlConnection connection = new SqlConnection(connectionString))

                          SqlCommand cmd = new SqlCommand("select QuestionId, Answer from Questions", connection);
                          try

                          connection.Open();
                          var reader = cmd.ExecuteReader();
                          while (reader.Read())

                          string questionId = (string)reader["QuestionId"];
                          string answer = (string)reader["Answer"];
                          if (!correctAnswerLookup.ContainsKey(questionId))

                          correctAnswerLookup.Add(questionId, answer);



                          catch (Exception e)

                          // your exception handling


                          return correctAnswerLookup;



                          And on your answer received event, you could just check the lookup and update the score. Handle the subtleties about validation and null check etc yourself.



                           private void OnAnswerSubmitted()

                          string currentQuestionId = ""; // however you get this in your UI.
                          string selectedAnswer = "";

                          if (_correctAnswerLookup[currentQuestionId] == selectedAnswer)

                          scoreCounter++;


                          lblScoreCounter.Text = scoreCounter.ToString();






                          share|improve this answer












                          I am assuming the number of quiz questions you have are in 100s at best and not in 1000000+s. So, rather than going to the database every time you receive an answer, you should grab all the question Id and their correct answer right in the beginning and store it in a dictionary. Then check the dictionary for correctness and update the score.



                          Below is a rough guideline, it's not an entirely working code, but that should give you a good enough idea, hopefully, else ask in the comment.



                          So in your constructor, you could make a call to retrieve all the answers. Like below:



                           private Dictionary<string, string> _correctAnswerLookup;
                          public Form1()

                          InitializeComponent();
                          _correctAnswerLookup = GetCorrectAnswerByQuestionLookup();


                          private Dictionary<string, string> GetCorrectAnswerByQuestionLookup()

                          Dictionary<string, string> correctAnswerLookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                          using (SqlConnection connection = new SqlConnection(connectionString))

                          SqlCommand cmd = new SqlCommand("select QuestionId, Answer from Questions", connection);
                          try

                          connection.Open();
                          var reader = cmd.ExecuteReader();
                          while (reader.Read())

                          string questionId = (string)reader["QuestionId"];
                          string answer = (string)reader["Answer"];
                          if (!correctAnswerLookup.ContainsKey(questionId))

                          correctAnswerLookup.Add(questionId, answer);



                          catch (Exception e)

                          // your exception handling


                          return correctAnswerLookup;



                          And on your answer received event, you could just check the lookup and update the score. Handle the subtleties about validation and null check etc yourself.



                           private void OnAnswerSubmitted()

                          string currentQuestionId = ""; // however you get this in your UI.
                          string selectedAnswer = "";

                          if (_correctAnswerLookup[currentQuestionId] == selectedAnswer)

                          scoreCounter++;


                          lblScoreCounter.Text = scoreCounter.ToString();







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 9 at 23:08









                          NoSaidTheCompiler

                          1,72421734




                          1,72421734



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53234055%2fcompare-input-with-data-in-database-in-c-sharp-forms%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

                              Edmonton

                              Crossroads (UK TV series)