I'm trying to get my head around generating dynamic controls. I have a Button1_Clickevent that creates a CheckBoxList (id=cblAnswers) or a RadioButtonList (id=rblAnswers) depending on the value of a field in a database.
On Button3_Click event I want to be able to retrieve the selected values from the generated control and compare them with a List listOfCorrectAnswerIDs. If the selected values exactly match those in listOfCorrectAnswerIDs, I'd like to set a variable.
I can create the controls but how do I retrieve the selected values in Button3_Click and compare them with 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();
}
}
}