ASP.NET CheckBoxList DataBinding with Checked
So today I ran into an interesting issue with DataBinding to a CheckBoxList in ASP.NET 2.0; you cannot bind the checked state to the checked boxes. You can bind the Value and Text, but not the Checked state.
This leaves you with a few options for setting the checked state after databinding:
- Manually build the ListItem Collection for the CheckBoxList, setting the Value, Text and Selected values instead of databinding.
- Loop through the Items collection after databinding checking for each item.
- There is no number 3.
I decided to manually build a ListItem collection as follows:
foreach (DataRow dataRow in dataTable) {
string text =
Convert.ToString(dataRow[COLUMN_TEXT]);
string value = Convert.ToString(dataRow[COLUMN_VALUE]);
bool selected = Convert.ToBoolean(dataRow[COLUMN_SELECTED]);
ListItem newListItem = new ListItem();
newListItem.Text = text;
newListItem.Value = value;
newListItem.Selected = selected;
checkBoxListMyPreferencesShow.Items.AddRange(newListItem);
}