Pages

Thursday, September 9, 2010

C# ASP.NET CheckBoxList selecting items on OnDataBinding doesn't work, set it on OnDataBound instead

When I try to bind some objects to a CheckBoxList in the OnDataBinding method, it never seems to select it when I tell it to do so:

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.