【问题标题】:Create quiz application using C# and database使用 C# 和数据库创建测验应用程序
【发布时间】:2016-05-03 11:47:30
【问题描述】:

我刚刚完成了测验的添加部分,即管理员为客人添加问题的部分。

当我点击下一步按钮时,我只看到了我添加的最后一个问题。代码如下:

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();

我的问题是我不知道为什么我只看到最后一个问题,尽管我有多个问题。

【问题讨论】:

  • next button 的代码在哪里?
  • 一旦 while 循环退出,文本框将包含最后一行的详细信息..
  • 您正在阅读的每条记录都被下一条覆盖,最后您将获得最后一条
  • 您正在将结果写入循环内的相同文本框,因此它只会存储/显示最后分配的结果。
  • @MXD 这是下一个按钮的代码:D

标签: c# mysql sql database


【解决方案1】:

数据读取器正在循环遍历所有结果并覆盖查询中每一行的文本框值。

在上面的代码中,每次运行时,只会显示检索到的最后一行。

您可能会更好地检索数据并将其存储在数据结构中并重新编码下一个按钮以使用它。

例如

//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();

我在这里使用了数据表,但您也可以轻松地使用对象列表。 上面的代码只是将查询中的数据添加到数据表中,然后您可以在下一个按钮中编写更改行号的代码。

这只是一个艰难的开始,但它应该能让你走上正确的轨道

【讨论】:

  • 如何将其存储在数据结构中?
  • 如果您知道,我还有一个问题。我怎样才能在文本框中显示这个?一个文本框中的问题,另一个文本框中的 R1...
猜你喜欢
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 2017-12-11
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多