CheckboxList not installed Selected with ViewState disabled

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

I load it like this (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 mostly something like this (in the _Click server event for the button)

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

and MyLabel never adds any text to it. I can check with the debugger that it reaches the _Click foreach loop, but no items are selected. What could be the reason for this?

+4
source share
1 answer

If you fill it with every call to Page_Load, and not just with Page.IsPostback = false , then you redirect the client selection during the postback.

EDIT You must add your elements to the PreInit or Init event, after which you can correctly save the selected elements.

 protected void Page_Init(object sender, EventArgs e) { foreach (DataRow service in d.Tables[0].Rows) ... } 
+3
source

Source: https://habr.com/ru/post/1308183/


All Articles