【发布时间】:2014-09-07 03:37:49
【问题描述】:
我正在努力思考如何生成动态控件。我有一个 Button1_Clickevent,它根据数据库中字段的值创建 CheckBoxList (id=cblAnswers) 或 RadioButtonList (id=rblAnswers)。
在 Button3_Click 事件中,我希望能够从生成的控件中检索选定的值,并将它们与列表 listOfCorrectAnswerIDs 进行比较。如果所选值与 listOfCorrectAnswerIDs 中的值完全匹配,我想设置一个变量。
我可以创建控件,但如何在 Button3_Click 中检索选定的值并将它们与 List listOfCorrectAnswerIDs 进行比较?
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
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 questions_m WHERE question_id=1";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
reader = cmd.ExecuteReader();
if (reader.Read())
{
lblQuestion.Text = reader["question"].ToString();
if (reader["type"].ToString().Equals("C"))
{
CheckBoxList cblAnswers = new CheckBoxList();
cblAnswers.ID = "cblAnswers";
Page.Form.Controls.Add(cblAnswers);
}
else if (reader["type"].ToString().Equals("R"))
{
RadioButtonList rblAnswers = new RadioButtonList();
rblAnswers.ID = "rblAnswers";
Page.Form.Controls.Add(rblAnswers);
}
ViewState["QuestionID"] = reader["question_id"].ToString();
reader.Close();
string cmdText2 = "SELECT * FROM answers_m WHERE question_id=1";
MySqlCommand cmdAnswers = new MySqlCommand(cmdText2, conn);
reader = cmdAnswers.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());
}
}
reader.Close();
populateAnswers(listOfAnswers, listOfAnswerIDs);
}
else
{
reader.Close();
lblError.Text = "(no questions found)";
}
ViewState["listOfCorrectAnswerIDs"] = listOfCorrectAnswerIDs;
}
catch
{
lblError.Text = "Database connection error - failed to read records.";
}
finally
{
conn.Close();
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (((CheckBoxList)this.FindControl("cblAnswers")) != null)
{
List<string> selectedValues = ((CheckBoxList)this.FindControl("cblAnswers")).Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
for (int i = 0; i < selectedValues.Count; i++)
{
lblSelected.Text += selectedValues[i].ToString();
}
}
}
【问题讨论】:
标签: c# asp.net dynamic controls asp.net-controls