简体   繁体   中英

Create quiz application using C# and database

I just finished to make the add part of a quiz, the part where admin add questions for guest.

When I clicked next button I just see the last question I added. Here is the code:

SqlConnection con = new SqlConnection(@"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
        SqlDataReader reader = null;
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            textBox2.Text = (reader["Question"].ToString());
            textBox3.Text = (reader["R1"].ToString());
            textBox4.Text = (reader["R2"].ToString());
            textBox5.Text = (reader["R3"].ToString());
            textBox6.Text = (reader["R4"].ToString());
            if (textBox7.Text == (reader["R_correct"].ToString()))
               point = point + 1;
        }
        con.Close();

My problem is That I don't know why I see just the last question althoug in the table I have more than one question.

The datareader is looping through all the results and overwriting the textbox values for each row in the query.

In the code above, every time you run this, only the final row retrieved will be displayed.

You might be better retrieving the data and storing in a data structure and recoding the next button to use this.

eg

//Set up datatable with all questions

DataTable dt=new DataTable();
dt.column.Add("Question",typeof(string));
dt.column.Add("R1",typeof(string));
dt.column.Add("R2",typeof(string));
dt.column.Add("R3",typeof(string));
dt.column.Add("R4",typeof(string));
dt.column.Add("R_correct",typeof(int));

SqlConnection con = new SqlConnection(@"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
  DataRow dr=dt.NewRow();
  dr["Question"] = (reader["Question"].ToString());
  dr["R1"] = (reader["R1"].ToString());
  dr["R2"] = (reader["R2"].ToString());
  dr["R3"] = (reader["R3"].ToString());
  dr["R4"]  = (reader["R4"].ToString());
  dr["R_correct"]  = (reader["R_correct"]);
  dt.Rows.Add(dr);

}
con.Close();

I've used a datatable here but you could easily use a list of objects as well. The code above just adds the data from the query into a datatable and you can then, in your next button, write code that changes the row number.

This is just a rough start but it should get you on the right track

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM