使用MySQL数据填充ArrayList

时间:2014-07-09 17:53:51

标签: c# mysql asp.net arraylist datareader

我尝试使用数据库中的字段填充两个ArrayLists(listOfAnswers和listOfAnswerIDs)(' answer' answer' answer_id')。

当字符串cmdText中的question_id = 1时,以下代码似乎完全正常。但是,如果我将其更改为2或3,则ArrayLists仍为空,我不知道原因。有什么想法吗?

我认为用字符串cmdGetAnswersQuery做" SELECT * FROM回答WHERE question_id = 2"工程...

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

    ArrayList listOfAnswerIDs = new ArrayList();
    ArrayList listOfAnswers = new ArrayList();
    try
    {
        conn.Open();
        string cmdText = "SELECT * FROM questions_t WHERE question_id=2";
        MySqlCommand cmd = new MySqlCommand(cmdText, conn);
        cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
        cmd.Parameters["@ModuleID"].Value = ddlModules.SelectedValue;

        reader = cmd.ExecuteReader();

        if (reader.Read())
        {
            lblQuestion.Text = reader["question"].ToString();
            ViewState["QuestionID"] = reader["question_id"].ToString();
            ViewState["AnswerID"] = reader["correct_answer_id"].ToString();

            reader.Close();

            string cmdGetAnswersQuery = "SELECT * FROM answers WHERE question_id=@QuestionID";
            MySqlCommand cmdGetAnswers = new MySqlCommand(cmdGetAnswersQuery, conn);
            cmdGetAnswers.Parameters.Add("@QuestionID", MySqlDbType.Int32);
            cmdGetAnswers.Parameters["@QuestionID"].Value = ViewState["AnswerID"];

            reader = cmdGetAnswers.ExecuteReader();

            while (reader.Read())
            {
                listOfAnswerIDs.Add(reader["answer_id"].ToString());
                listOfAnswers.Add(reader["answer"].ToString());
            }
            reader.Close();
            populateAnswers(listOfAnswers, listOfAnswerIDs);
        }
        else
        {
            reader.Close();
            lblError.Text = "(no questions found)";
        }
    }
    catch
    {
        lblError.Text = "Database connection error - failed to insert record.";
    }
    finally
    {
        conn.Close();
    }

实际的数据库内容如下所示: http://i.imgur.com/3S4lV60.png http://i.imgur.com/8A913xF.png

1 个答案:

答案 0 :(得分:2)

我不能肯定这是问题,但我要看的第一件事就是这行代码:

cmdGetAnswers.Parameters["@QuestionID"].Value = ViewState["AnswerID"];

我怀疑你希望那是ViewState["QuestionID"]