C# quiz code not working properly - c#

I am making a quiz which was working up to a point but after trying to increase its complexity it doesn't work completely as it should. All that happens at the moment is that the possible answers in my Access database table are binded to each radio button on my C# form.
This part is OK, however, it is no longer telling me after clicking on my button whether or not the answer I have selected is correct or not. I am using a label at the moment to tell the user if the answer is correct.
Here is my code:
namespace WindowsFormsApplication1
{
public partial class quizQuestions : Form
{
public quizQuestions()
{
InitializeComponent();
}
//int questionNumber;
//String correctAnswer;
private void WindowsAnalysisQuiz_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\quizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
//{
//open connection
conGet.Open();
String correctAnswer;
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM quizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
label1.Text = reader["Question"].ToString();
radioButton1.Text = reader["Answer 1"].ToString();
radioButton2.Text = reader["Answer 2"].ToString();
radioButton3.Text = reader["Answer 3"].ToString();
radioButton4.Text = reader["Answer 4"].ToString();
correctAnswer = reader["Correct Answer"].ToString();
//questionNumber = 1;
conGet.Close();
}
private void btnNextQuestion_Click(object sender, EventArgs e)
{
String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\quizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
//cmdGet.CommandText = "SELECT * FROM quizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
String chosenAnswer = "";
int chosenCorrectly = 0;
if (radioButton1.Checked)
{
chosenAnswer = reader["Answer 1"].ToString();
}
else if (radioButton2.Checked)
{
chosenAnswer = reader["Answer 2"].ToString();
}
else if (radioButton3.Checked)
{
chosenAnswer = reader["Answer 3"].ToString();
}
else
{
chosenAnswer = reader["Answer 4"].ToString();
}
if (chosenAnswer == reader["Correct Answer"].ToString())
{
//chosenCorrectly++;
label2.Text = "You have got this answer correct";
//label2.Text = "You have got " + chosenCorrectly + " answers correct";
}
else
{
MessageBox.Show("That is not the correct answer");
}
}
}
}
}
So to summarise, the possible answers are loaded into the form OK, but when I press the button on the form to determine if the correct answer has been chosen, nothing at all happens.

You are not binding the btnNextQuestion_Click anywhere in your code, and you are not giving a cmdGet.CommandText in your btnNextQuestion_Click function. You may have to be more specific on what doesnt happen. Have you debugged it?

If truly "nothing" happens, then you should check that the click event of the button is still bound to the event handler.
You have commented out the line where you set the CommandText for the query, so you are trying to execute the command with not query set, which should give you an exception.

I think there is something terribly wrong in what you have got there. You are assigning the answers to the Text property and already have the correct answer in a string.
Just check the same against the checked RadioButton Text and you would know.
Also its difficult to guess what you are querying in the btnNextQuestion_Click event and i have my reservations as its actually the same question which is currently displayed and with an answer chosen by the user.

Related

Ticket Booking System: Comparing two strings [duplicate]

This question already exists:
Ticket Booking System: Database access issue
Closed 3 years ago.
Okay so I'm basically trying to verify whether the username being entered is a duplicate but there's a problem in the string comparison inside the while loop
I tried using a temp label to verify that the values are being extracted correctly.
protected void BtnConfirmSignup_Click(object sender, EventArgs e)
{
int f = 0;
SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLlocalDB;Initial Catalog=traveller;Integrated Security=True;Pooling=False");
SqlCommand cmd;
SqlDataReader read;
/*DEBUG: Prevent duplicate usernames*/
try
{
Session["user"] = TxtUsrName.Text;
Session["pass"] = TxtPsswd.Text;
Session["email"] = TxtEmail.Text;
//Label6.Text = "Faf";
// if ((Label6.Text).Equals(TxtUsrName.Text))
//{
// Label6.Text = "dafuqqqq";
//}
//{
// Label6.Text = "wtf";
// Label6.Text = TxtUsrName.Text;
//}
cmd = new SqlCommand("select Name from Useriden", con);
con.Open();
read = cmd.ExecuteReader();
while (read.Read())
{
Label6.Text = read["Name"].ToString();
Label1.Text = "aaa";
//Label6.Text = "Faf";
if ((Label6.Text).Equals(TxtUsrName.Text))
{
f = 1;
//Label6.Text = "Duplicate Username";
break;
}
}
if (f == 1)
{
Label6.Text = "Duplicate Username";
}
else if (f == 0)
{
Response.Redirect("SignUpNext.aspx");
}
}
catch (Exception ex)
{
LabelUserName.Visible = true;
LabelUserName.Text = ex.Message;
con.Close();
ViewState["Caption"]=ex.Message;
}
}
Expected: I'm entering a duplicate name so it should the change the text of the label to Duplicate Username but it instead navigates to the next page/The value of f never changes.
To add to what #EdPlunkett pointed out with the Ordinal Case... You should also make sure there are no extra spaces.
Label6.Trim().Text.Equals(TxtUsrName.Text.Trim(), StringComparison.OrdinalIgnoreCase)
Side note: You also don't seem to be closing your SqlConnection unless there is an exception. You should maybe use using()

System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

I am new at coding and currently trying to make this barcode tracker program. So far I searched and found what i need but now I couldn't find the answer of this problem (or couldn't understand what people tried to say). So here is my problem:
I am using Ms Access as database but, as numeric datatype Access allows me to enter maximum 10 digit numbers. Also, I know that some barcodes include alphabetic characters so I have to change the datatype to text. If the column's datatype which contains the barcodes is numeric, program works. When i change the column's datatype to text, program gives data type mismatch error.
Here is my code:
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Barcode\\Database.accdb; Persist Security Info=False");
OleDbDataReader DataReader;
OleDbCommand command;
bool flag = false;
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
public void txt_UPC_KeyDown(object sender, KeyEventArgs e)
{
if ((txt_UPC.Text == "") && (e.KeyCode == Keys.Enter))
{
e.Handled = true;
}
else
{
if (e.KeyValue == (char)Keys.Enter)
{
connection.Open();
string SelectQuery = "SELECT * FROM Products where [UPC]=" + txt_UPC.Text.ToString();
command = new OleDbCommand(SelectQuery, connection);
DataReader = command.ExecuteReader(); **//Error occurs here...**
while (DataReader.Read())
{
txtProduct.Text = DataReader["Product"].ToString();
txtPrice.Text = DataReader["Price"] + " ₺";
if (DataReader["UPC"].ToString() == txt_UPC.Text)
{
flag = true;
}
}
if (flag == true)
{
Test.Text = "Known Product";
txt_UPC.Text = "";
flag = false;
}
else
{
Test.Text = "Unknown Product";
}
connection.Close();
}
}
}
}
Suggest use apostrophe delimiters for text type field parameter.
string SelectQuery = "SELECT * FROM Products where [UPC]='" + txt_UPC.Text.ToString() + "'";
You need fully a formed SQL Server expression. You currently have
string SelectQuery = "SELECT * FROM Products where [UPC]=" + txt_UPC.Text.ToString();
Assuming that txt_UPC.Text is a string, you probably need to do this instead:
string SelectQuery = "SELECT * FROM Products where [UPC]= '" + txt_UPC.Text.ToString() + "'";
That encloses your string in the SQL-language mandated single quotes. For what it's worth, you probably don't need the .ToString() on that either.
And, it's a really bad idea to concatenate SQL like you are doing, particularly if you include user inputted text. Read up on "SQL Injection" and use parameterized SQL instead.

Why the while loop is used in this database connection?

Currectly I am studying and learning and I just wanted to know some logic of this database connection in C#. I wanted to know why the while loop is used I means if I don't use it, will it affect the program or will the program run fine if I take it out. I just wanted to know is it wise to use it or just take it out from the program. Can someone please help me ?? Thank you
private bool filled;
public DataSet ds = new DataSet();
private void bnt_displaylog_Click(object sender, EventArgs e)
{
try
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Elevator_Database.accdb;";
string dbcommand = "Select * from Log;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
//MessageBox.Show("Connection Open ! ");
**while (filled == false)**
{
adapter.Fill(ds);
filled = true;
}
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
string message = "Error in connection to datasource";
string caption = "Error";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
}
database_listbox.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
database_listbox.Items.Add(row["Date"] + "\t\t" + row["Time"] + "\t\t" + row["Action"]);
}
}
That's just code that was written in a very unclear manner. The while loop will never loop at all. The loop body will either be executed once, or not at all, depending on the value of filled.
In other words, the code could have been written more clearly as:
conn.Open();
if( ! filled )
{
adapter.Fill(ds);
filled = true;
}
conn.Close();
But even then, the code is doing the wrong thing. Think about the case where filled is true. The code that's actually executed is:
conn.Open();
conn.Close();
and what's the point of doing that?
In any case, what the code actually does, either with while or if, is call adapter.Fill(ds) only the first time through. Given that, we should skip setting up the connection entirely when we don't make that call. And let's refactor the code to make it a bit more clear:
private bool filled = false;
public DataSet ds = new DataSet();
private void bnt_displaylog_Click(object sender, EventArgs e)
{
loadDisplayLog();
database_listbox.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
database_listbox.Items.Add(
row["Date"] + "\t\t" + row["Time"] + "\t\t" + row["Action"]
);
}
}
private void loadDisplayLog(object sender, EventArgs e)
{
if( filled ) return;
try
{
string dbconnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Elevator_Database.accdb;";
string dbcommand = "Select * from Log;";
OleDbConnection conn = new OleDbConnection(dbconnection);
OleDbCommand comm = new OleDbCommand(dbcommand, conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(comm);
conn.Open();
adapter.Fill(ds);
conn.Close();
filled = true;
}
catch (Exception)
{
MessageBox.Show("Can not open connection ! ");
string message = "Error in connection to datasource";
string caption = "Error";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
}
}
There are still some issues with the exception handling in this code - will the connection be closed if adapter.Fill(ds); throws an exception? Oops. But I'll leave the rest as an exercise for the reader...

Radio Button Value from Database C#

I am trying to get my program to read a value from a particular cell in my Access database so that I can assign that value to the text property of a radio button. I am however getting an error I can't figure out the problem to. This is my code:
private void WindowsAnalysisQuiz_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\WindowsAnalysisQuiz.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
//cmdGet.CommansText = "SELECT
cmdGet.CommandText = "SELECT Question FROM WindowsAnalysisQuiz ORDER BY rnd()";
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
label1.Text = reader["Question"].ToString();
radioButton.Text = cnString["Quiz"].Rows[0]["Correct Answer"].ToString();
radioButton1.Text = reader["Answer2"].ToString();
radioButton2.Text = reader["Answer3"].ToString();
radioButton3.Text = reader["Answer4"].ToString();
conGet.Close();
}
}
I am having the problem with the line beginning with radioButton.Text. Apparently it has some invalid arguments and argument 1 cannot convert from string to int
It looks like you are using several different RadioButtons, when you might really want a RadioButtonList.
If you have a RadioButtonList, it is easy to bind something to it, in essence create a list (from your database or whatever) and then bind this to the radio button list..something like
var de = new List<string>();
de.Add("1");
de.Add("2");
de.Add("3");
RadioButtonList1.DataSource = de;
RadioButtonList1.DataBind();
Shouldn't your code be something like the following:
radioButton.Text = reader["Correct Answer"].ToString();
And change your select statement to:
cmdGet.CommandText = "SELECT Question, [Correct Answer], Answer2, Answer3, Answer4 FROM WindowsAnalysisQuiz ORDER BY rnd()";

C# Object Problem - Can't Solve It

I'm getting the error 'Object reference not set to an instance of an object'. I've tried looking at similar problems but genuinely cannot see what the problem is with my program. The line of code that I am having an error with is:
labelQuestion.Text = table.Rows[0]["Question"].ToString();
Here is my code in its entirety:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Sql;
using System.Data.SqlClient;
namespace Quiz_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String chosenAnswer, correctAnswer;
DataTable table;
private void Form1_Load(object sender, EventArgs e)
{
//declare connection string using windows security
string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
//{
//open connection
conGet.Open();
//String correctAnswer;
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()";
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
labelQuestion.Text = table.Rows[0]["Question"].ToString();
radioButton1.Text = table.Rows[0]["Answer 1"].ToString();
radioButton2.Text = table.Rows[0]["Answer 2"].ToString();
radioButton3.Text = table.Rows[0]["Answer 3"].ToString();
radioButton4.Text = table.Rows[0]["Answer 4"].ToString();
correctAnswer = table.Rows[0]["Correct Answer"].ToString(); ;
conGet.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb";
//declare Connection, command and other related objects
OleDbConnection conGet = new OleDbConnection(cnString);
OleDbCommand cmdGet = new OleDbCommand();
//try
{
//open connection
conGet.Open();
cmdGet.CommandType = CommandType.Text;
cmdGet.Connection = conGet;
cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; // select all columns in all rows
OleDbDataReader reader = cmdGet.ExecuteReader();
reader.Read();
if (radioButton1.Checked)
{
chosenAnswer = reader["Answer 1"].ToString();
}
else if (radioButton2.Checked)
{
chosenAnswer = reader["Answer 2"].ToString();
}
else if (radioButton3.Checked)
{
chosenAnswer = reader["Answer 3"].ToString();
}
else
{
chosenAnswer = reader["Answer 4"].ToString();
}
if (chosenAnswer == reader["Correct Answer"].ToString())
{
//chosenCorrectly++;
MessageBox.Show("You have got this answer correct");
//label2.Text = "You have got " + chosenCorrectly + " answers correct";
}
else
{
MessageBox.Show("That is not the correct answer");
}
}
}
}
}
I realise the problem isn't too big but I can't see how my declaration timings are wrong
You never initialize table, so it will be null when you try to access its Rows property.
You don't actually need the DataTable in this instance, though. You can access the properties directly from the OleDbDataReader (which you do initialize.) See here for details (look at the Get***() family of methods.)
Something like:
labelQuestion.Text = reader.GetString(reader.GetOrdinal("Question"));
And so forth for the rest of the columns.
If you do choose to use table, then omit the reader.Read() line and add:
table = new DataTable();
table.Load(reader);
The problem is that your table is not initialized. Therefore, when you try to access table.row[0] you get this error message.
And If there was no question column, you would probably get an error like
Column ‘Question’ does not belong to table.
Hence, at this point it is not ok. to say whether there is 'Question' column or not. First, you need to fill your table.
Right after you call ExecuteReader () in Form1_Load you need
table = new DataTable();
table.Load (reader);
Error object reference Null:
try
{
OleDbCommand com;
// OleDbConnection con = new OleDbConnection(ConnectionString);
cn.Open();
string str = "select *from DatabaseLogin where user_id='" + textBox2.Text + "'";
com = new OleDbCommand(str, cn);
OleDbDataReader reader = com.ExecuteReader();
while (reader.Read())
{
checkedListBox1.Items.Add(reader["stckdemge"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(" " + ex);
}
Either the table has no rows, or there is no "Question" column, or that the column has a Null value in it.
Consider breaking the assignment up into multiple steps to help you diagnose the issue.
EDIT:
Or, as sharper eyes have already noted, it's because you've not assigned anything to 'table' (d'oh).
The comment about breaking up the assignment is a useful diagnostic method, though.

Categories