views:

270

answers:

1

I have a CheckboxList that seems to load and do everything right, except for when I do a postback, it will not have the Item.Selected property set. I have viewstate disabled for the entire page.

I load it like so(inside Page_Load on every load):

foreach (DataRow service in d.Tables[0].Rows)
{
  cblServices.Items.Add(new ListItem((string)service["description"], service["id"].ToString()));
}

My markup is simple:

<asp:CheckBoxList runat="server" ID="cblServices" Width="300px"></asp:CheckBoxList>

and then, I use basically something like this(in a _Click serverside event for a button)

foreach(ListItem item in cblServices.Items){
  if(item.Selected){
    MyLabel.Text+="selected: "+item.Value+item.Text;
  }
}

and MyLabel never has any text added to it. I can verify with the debugger that it does reach the _Click's foreach loop, but no item is ever selected. What could be the cause of this?

+2  A: 

If you're filling it on every Page_Load call, not only when Page.IsPostback = false then you're reseting the client selection on postback.

EDIT You should add your items on the PreInit or Init event, then you'll be able to keep the selected items correctly.

protected void Page_Init(object sender, EventArgs e)
{
    foreach (DataRow service in d.Tables[0].Rows)
    ...
}
Claudio Redi
@Cla yea, but if I do not add the items again(when Page.IsPostback==true), then when it gets to _Click's foreach, it doesn't have any ListItems
Earlz
@Cla (your edit) I do not have access to the Page_PreInit(working in a UserControl). Plus, that doesn't even make sense because the controls don't exist yet at PreInit
Earlz
@Earlz: The only way to keep the state of dynamically added controls is adding them on init / preInit event. msdn.microsoft.com/en-us/library/…. Could you try with the OnInit event instead. Didn't know it was a User Control
Claudio Redi
Yea, I'm trying to get my code to move. It's not the most trivial thing to just move though because it's dynamic..
Earlz
Ok, now it works. Accepting this even though I hate this answer because it means that some dynamic things have to somehow be moved into Page_Init. I hate the page lifecycle..
Earlz