C# C-使用数据库中的数据填充列表
我在ViewState中存储了一个包含10个不同数字的QuestionID列表,在ViewState中存储了一个int计数器questionCounter,我打算使用它访问第一个列表中的不同数字 但是,当我将ViewState[questionCounter]的值增加1时,ListoFaswirids和ListoFaswers的内容在下面的代码中保持完全相同。为什么会这样C# C-使用数据库中的数据填充列表,c#,asp.net,list,viewstate,C#,Asp.net,List,Viewstate,我在ViewState中存储了一个包含10个不同数字的QuestionID列表,在ViewState中存储了一个int计数器questionCounter,我打算使用它访问第一个列表中的不同数字 但是,当我将ViewState[questionCounter]的值增加1时,ListoFaswirids和ListoFaswers的内容在下面的代码中保持完全相同。为什么会这样 protected void getAnswers() { string connStr = Configurati
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;
}
ViewState键区分大小写。在getAnswers中使用问号计数器,在getNextQuestion中使用问号计数器。选择一个并保持一致。在哪里递增ViewState[questionCounter]或questionCounter?不应该有类似于以下字符串的内容:cmdText=SELECT*,其中question_id=@QuestionID;使用存储过程。这个函数在哪里called@BubbleHearth在我在原始帖子中添加的另一个函数中。@Bhav-在ViewState中有多少项?就一个?或者你得到10个?你确认ListofQuestionID实际上包含一个不同的问题ID列表了吗?您编写的代码看起来应该可以工作,尽管您确实应该处理其中的一些对象。保存come const string值以便于使用,有助于防止此类错误。
protected void btnNext_Click(object sender, EventArgs e)
{
.........
getNextQuestion();
}
protected void getNextQuestion()
{
int questionCounter = Convert.ToInt32(ViewState["QuestionCounter"]);
..........
getAnswers();
................
questionCounter += 1;
ViewState["QuestionCounter"] = questionCounter;
}