Reputation: 46340
I have a CheckBoxList in my page, with the DataTextField and DataValueField attributes set, is there an attribute that I can use to specify a property that indicates if it should be checked?
I'm hoping to just set the datasource, and not have to have any code behind to set the checked property. Possible?
Upvotes: 4
Views: 5358
Reputation: 3911
lock at this example:
string[] strUserRoles = Roles.GetRolesForUser("Ali");
foreach (var item in Roles.GetAllRoles())
{
chkRoleList.Items.Add(new ListItem()
{
Text = item,
Value = item,
Selected = strUserRoles.Contains(item)
});
}
Note: when you bind CheckListBox, you must set Both of Text and Value of each Item.
Upvotes: 0
Reputation: 47726
No it's not possible because the control uses the same binding as other controls such as ListBox, DropDownList, RadioButtonList, etc.
As per MSDN:
To set multiple selections in a list control programmatically loop through the control's Items collection and set the Selected property of every individual item.
You could implement the OnDataBinding of the CheckListBox and then do a lookup for each item that gets bound but it would probably just be easier to do it all in one place.
Upvotes: 3