Compare input with data in database in c# forms
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
add a comment |
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
add a comment |
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
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
c# database forms
edited Nov 9 at 22:27
CSharpRocks
3,96411221
3,96411221
asked Nov 9 at 22:25
tonique
62
62
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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.
add a comment |
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();
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
edited Nov 9 at 22:42
answered Nov 9 at 22:34
DMarczak
1119
1119
add a comment |
add a comment |
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();
add a comment |
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();
add a comment |
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();
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();
answered Nov 9 at 23:08
NoSaidTheCompiler
1,72421734
1,72421734
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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