3

I dynamically create a RadioButtonList or a CheckBoxList depending on a condition within a Button_Click event (which works).

protected void btnGetQuestion_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>();

    int questionCounter = 0;

    //get questionIDs and store in ViewState["listOfQuestionIDs"]
    getListOfQuestionIDs();

    try
    {
        conn.Open();

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

        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);
            }

            questionCounter += 1;
            ViewState["questionCounter"] = questionCounter;
            ViewState["QuestionID"] = Convert.ToInt32(reader["question_id"]);
            reader.Close();

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

            reader = cmdAnswers.ExecuteReader();

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

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

I want to create a method that I can run in another button click event (btnNext_Click) that will remove the RadioButtonList or CheckBoxList if one exists.

I've tried the following but it doesn't seem to work:

protected void clearAnswers()
{
    if (((CheckBoxList)this.FindControl("cblAnswers")) != null)
    {
        Page.Form.Controls.Remove(this.FindControl("cblAnswers"));
    }

    if (((RadioButtonList)this.FindControl("rblAnswers")) != null)
    {
        Page.Form.Controls.Remove(this.FindControl("rblAnswers"));
    }
}

UPDATE: I think the issue I had occured with the repopulation of the RadioButtonList/CheckBoxList. If I cleared each item before repopulating them, that resolved my problem.

    if (((CheckBoxList)this.FindControl("cblAnswers")) != null)
    {
        ((CheckBoxList)this.FindControl("cblAnswers")).Items.Clear();
        foreach (int num in numbers)
        {
            ((CheckBoxList)this.FindControl("cblAnswers")).Items.Add(ans[num - 1]);
        }
    }

    if (((RadioButtonList)this.FindControl("rblAnswers")) != null)
    {
        ((RadioButtonList)this.FindControl("rblAnswers")).Items.Clear();
        foreach (int num in numbers)
        {
            ((RadioButtonList)this.FindControl("rblAnswers")).Items.Add(ans[num - 1]);
        }
    }
Bhav
  • 1,957
  • 7
  • 33
  • 66
  • Does it throw any kind of error or exception when you run that? – Pseudonym Jul 16 '14 at 11:56
  • @bhav what exactly doesn't work? Please explain more. If you do a full postback then your dynamic controls will be gone anyway... – therak Jul 16 '14 at 12:00
  • @PseudoNym01 No, the following line of code Page.Form.Controls.Remove(this.FindControl("cblAnswers")); doesn't seem to remove the CheckBoxList and I don't receive any errors or exceptions. – Bhav Jul 16 '14 at 12:10
  • What context has "this" when you use with FindControl? – chemitaxis Jul 16 '14 at 12:10
  • and you are sure that line is being executed? – Pseudonym Jul 16 '14 at 12:12
  • Ah, that line seems to work in isolation. However, when I then recreate a new CheckBoxList/RadioButtonList with the same id, the previous list items seem to still exist. I've found a workaround by clearing the controls before repopulating them. – Bhav Jul 16 '14 at 12:32

1 Answers1

0

Try this:

protected void clearAnswers()
{

    CheckBoxList cblAnswers = (CheckBoxList)this.FindControl("cblAnswers");
    RadioButtonList rblAnswers = (RadioButtonList)this.FindControl("rblAnswers");


    if (cblAnswers != null)
    {
        Page.Form.Controls.Remove(cblAnswers);
    }

    if (rblAnswers != null)
    {
        Page.Form.Controls.Remove(rblAnswers);
    }
}
chemitaxis
  • 13,889
  • 17
  • 74
  • 125
  • Cannot implicitly convert type 'System.Web.UI.Control' to 'System.Web.UI.WebControls.CheckBoxList – Bhav Jul 16 '14 at 12:22