2

I need to dynamically add CheckBoxList on the SelectedIndexChanged event of DropDownList. I have achieved this but I cannot retain its value on postback.

Here’s what I have done so far:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    loadTracks();//Needs to generated dynamically
}

protected void Page_Load(object sender, EventArgs e)
{

    if (!Page.IsPostBack)
    {
    loadDegrees();
    }
    loadTracks();
}

public void loadTracks()
{
    try
    {
        ConfigurationDB objConfig = new ConfigurationDB();
        DataSet ds = objConfig.GetTracksByDegreeID(
            Convert.ToInt32(ddlDegree.SelectedValue.ToString()));
        CheckBoxList CbxList = new CheckBoxList();

        CbxList.ID = "Cbx";
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            CbxList.Items.Add(new ListItem(ds.Tables[0].Rows[i]["Track_Name"]
                .ToString(), ds.Tables[0].Rows[i]["ID"].ToString()));
        }
        ph.Controls.Add(CbxList);
        ViewState["tracks"] = true;
    }
    catch(Exception ex)
    {
        Response.Write(ex.Message);
    }
}

//For testing, I added a button and on its click I have added this code

protected void btnDetails_Click(object sender, EventArgs e)
{
    CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
    foreach (ListItem ex in Cbx.Items)
    {
        if (ex.Selected)
        {
            Response.Write(String.Format("You selected: <i>{0}</i> <br>", ex.Value));
        }
    }
}

2 Answers 2

4

Might be a typo:

CbxList.ID = "Cbx";

v.s.

CheckBoxList Cbx = (CheckBoxList)ph.FindControl("chk");
Sign up to request clarification or add additional context in comments.

2 Comments

Andomar if i populate the checkboxlist cbx. I mean if i dont add it to a placeholder. The results are appended again and again. i do CbxList.Items.Clear(); Then i also loss it id which i need the selecedIndexChange of checkboxlist. I am stuck. will you suggest something
@user1057735: Only add the items if (!IsCallback && !IsPostBack). Feel free to ask new question instead of adding a comment; then all of SO gets a chance to answer!
0

You can try it without changing the code and use pre PreRender just run you loadTracks()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.