ASP.NET CheckBoxList DataBinding Question

后端 未结 4 1927
时光取名叫无心
时光取名叫无心 2020-12-29 21:37

Is it possible to DataBind an ASP.NET CheckBoxList such that a string value in the data becomes the label of the check box and a bool value checks/unchecks the box?

4条回答
  •  -上瘾入骨i
    2020-12-29 22:12

    It's not possible using markup. What you can do is to bind the checkboxlist like you wanted it to work - with the bool in the DataValueField, and then simply add this as OnDataBound event.

    protected void myCheckBoxList_DataBound(object sender, EventArgs e)
        {
            foreach (ListItem item in myCheckBoxList.Items)
            {
                item.Selected = bool.Parse(item.Value);
            }
        }
    

    The difference between this solution and the one proposed by Jose Basilio is that this one works with all kind of databinding methods. For example binding with a SelectMethod using the new ModelBinding feature in v4.5.

提交回复
热议问题