protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); chkBxLstProducts.DataSource = Product.GetAll(); chkBxLstProducts.DataBind(); foreach (var item in chkBxLstProducts.Items.Cast()) { item.Selected = ((ICollection)FieldValue).Cast () .Any(p => p.ProductId == Convert.ToInt32(item.Value)); } }
When I move the selection code into the OnDataBound method, it works:
protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); chkBxLstProducts.DataSource = Product.GetAll(); chkBxLstProducts.DataBind(); } protected void OnDataBound(object sender, EventArgs e) { foreach (var item in chkBxLstProducts.Items.Cast()) { item.Selected = ((ICollection)FieldValue).Cast () .Any(p => p.ProductId == Convert.ToInt32(item.Value)); } }
I’m not 100% sure, but I think it’s because the OnDataBinding event occurs before the CheckBoxList is rendered. So after it’s rendered, everything is wiped clean and we lose the selection. Selecting items after OnDataBound ensures it gets rendered.