C# - 使用数据库中的数据填充列表

时间:2014-07-16 16:55:04

标签: c# asp.net list viewstate

我有一个List(listOfQuestionIDs)存储在ViewState中的10个不同的数字和一个存储在ViewState中的int计数器(questionCounter),我打算用它来访问第一个列表中的不同数字。

但是,当我将ViewState [" questionCounter"]的值递增1时,listOfAnswerIDs和listOfAnswers的内容在下面的代码中保持完全相同。这是为什么?

protected void getAnswers()
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);
    MySqlDataReader reader;

    List<int> listOfQuestionIDs = (List<int>)(ViewState["listOfQuestionIDs"]);
    int questionCounter = Convert.ToInt32(ViewState["questionCounter"]);

    List<string> listOfAnswerIDs = new List<string>();
    List<string> listOfAnswers = new List<string>();
    List<string> listOfCorrectAnswerIDs = new List<string>();

    try
    {
        conn.Open();

        string cmdText = "SELECT * FROM answers WHERE question_id=@QuestionID";
        MySqlCommand cmd = new MySqlCommand(cmdText, conn);
        cmd.Parameters.Add("@QuestionID", MySqlDbType.Int32);
        cmd.Parameters["@QuestionID"].Value = Convert.ToInt32(listOfQuestionIDs[questionCounter]);

        reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            listOfAnswerIDs.Add(reader["answer_id"].ToString());
            listOfAnswers.Add(reader["answer"].ToString());

            if (reader["correct"].ToString().Equals("Y"))
            {
                listOfCorrectAnswerIDs.Add(reader["answer_id"].ToString());
            }
        }

        for (int i = 0; i < listOfAnswerIDs.Count; i++)
        {
            lblTitle.Text += listOfAnswerIDs[i].ToString();
        }

        reader.Close();

        populateAnswers(listOfAnswerIDs.Count, listOfAnswers, listOfAnswerIDs);
    }
    catch
    {
        lblError.Text = "Database connection error - failed to read records.";
    }
    finally
    {
        conn.Close();
    }

    ViewState["listOfQuestionIDs"] = listOfQuestionIDs;
    ViewState["listOfCorrectAnswerIDs"] = listOfCorrectAnswerIDs;
}

我在这里增加了QuestionCounter:

protected void btnNext_Click(object sender, EventArgs e)
{
    .........
    getNextQuestion();
}

protected void getNextQuestion()
{
    int questionCounter = Convert.ToInt32(ViewState["QuestionCounter"]);
    ..........
    getAnswers();
    ................
    questionCounter += 1;
    ViewState["QuestionCounter"] = questionCounter;
}

1 个答案:

答案 0 :(得分:3)

ViewState键区分大小写。在getAnswers()中,你使用&#34; questionCounter&#34;在getNextQuestion()中,你使用&#34; QuestionCounter&#34;。选择一个并保持一致。