我的页面中有一个 CheckBoxList,设置了 DataTextField 和 DataValueField 属性,是否有一个属性可以用来指定一个属性来指示是否应该检查它?
我希望只设置数据源,而不需要任何代码来设置选中的属性。可能的?
我的页面中有一个 CheckBoxList,设置了 DataTextField 和 DataValueField 属性,是否有一个属性可以用来指定一个属性来指示是否应该检查它?
我希望只设置数据源,而不需要任何代码来设置选中的属性。可能的?
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.
锁定此示例:
string[] strUserRoles = Roles.GetRolesForUser("Ali");
foreach (var item in Roles.GetAllRoles())
{
chkRoleList.Items.Add(new ListItem()
{
Text = item,
Value = item,
Selected = strUserRoles.Contains(item)
});
}
注意:绑定 CheckListBox 时,必须设置每个 Item 的 Text 和 Value。