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?
I made a custom control for this, after getting tired of the OnItemDataBound-binding.
It will let you bind the Selected attribute. You can easily make the same control for RadioButtonList by changing what the custom control derives from.
To use this, simply add the DataCheckedField attribute when you create the control in your markup. Remember to reference the custom controls in your web.config file.
Markup
Code for the control
public class SimpleCheckBoxList : System.Web.UI.WebControls.CheckBoxList
{
public string DataCheckedField
{
get
{
string s = (string)ViewState["DataCheckedField"];
return (s == null) ? String.Empty : s;
}
set
{
ViewState["DataCheckedField"] = value;
if (Initialized)
OnDataPropertyChanged();
}
}
protected override void PerformDataBinding(IEnumerable dataSource)
{
if (dataSource != null)
{
if (!this.AppendDataBoundItems)
this.Items.Clear();
if (dataSource is ICollection)
this.Items.Capacity = (dataSource as ICollection).Count + this.Items.Count;
foreach (object dataItem in dataSource)
{
ListItem item = new ListItem()
{
Text = DataBinder.GetPropertyValue(dataItem, DataTextField).ToString(),
Value = DataBinder.GetPropertyValue(dataItem, DataValueField).ToString(),
Selected = (DataCheckedField.Length > 0) ? (bool)DataBinder.GetPropertyValue(dataItem, DataCheckedField) : false
};
this.Items.Add(item);
}
}
}
}