views:

523

answers:

2

I have a web form that will dynamically create a number of checkboxlist filled with data based on the number of row in database. Then this is added to a placeholder to be displayed.

theres a button when clicked, will add the selected check boxes value into database but right now when the button is clicked and after the postback, the page will show the error "System.NullReferenceException".

the following code is written in Page_Load in (!Page.IsNotPostBack) and in a loop that will dynamically create a number of checkboxlist:

                CheckBoxLis chkContent = new CheckBoxList();
                chkContent.ID = chkIDString; //chkIDString is an incremental int based on the row count 
                chkContent.RepeatDirection = RepeatDirection.Horizontal;                    
                foreach (List<t> contentList in List<t>) //data retrieved as List<t> using LINQ
                {
                    ListItem contents = new ListItem();
                    contents.Text = contentList.Title;
                    contents.Value = contentList.contentID.ToString();
                    chkContent.Items.Add(contents);
                }

                plcSchool.Controls.Add(chkContent); //plcSchool is my placeholder
                plcSchool.Controls.Add(new LiteralControl("<br>"));



protected void btnAdd_Click(object sender, EventArgs e)
{
    CheckBoxList cbl = Page.FindControl("chkContent4") as CheckBoxList;
    Response.Write(cbl.SelectedValue.ToString()); // now im just testing to get the value from one of the checkboxlist     
}

Anyone able to help, as it seems the controls are not recreated after the postback, therefore it can't find the control and throwing the null reference exception.

+1  A: 

The short answer is that dynamically created controls have to be created each postback, otherwise they won't be present. You need to create the controls each time.

You can do this most easily by overriding in CreateChildControls() This will create the controls at the proper time, and later in the page lifecycle, their ViewState will be populated and they'll pickup any settings stored there.

In your case, just move the control creation outside of the !Page.IsPostback block.

Nick Craver
+1  A: 

Edit: This is actually two problems -- the controls aren't present, and their values won't populate. Moving your control creation outside of the Page.IsPostback check will get them created, but the values chosen won't repopulate automatically that late in the page lifecycle.

So the problem is that your controls aren't present when the page goes to the viewstate -- a cheap way to get around this is to create dynamic controls in page_init.

This is the page I always go to with these types of questions: http://msdn.microsoft.com/en-us/library/ms178472.aspx

Jason M
Thanks a lot Jason, that helped solved my problem.
newName