Dynamically created "CheckBoxList" in placeholder controls throwing null reference exception error d
Posted
by newName
on Stack Overflow
See other posts from Stack Overflow
or by newName
Published on 2010-03-24T01:23:56Z
Indexed on
2010/03/24
1:33 UTC
Read the original article
Hit count: 556
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.
© Stack Overflow or respective owner