views:

2502

answers:

2

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?

On my asp.net webform I have a CheckBoxList like this:

<asp:CheckBoxList runat="server" ID="chkListRoles" DataTextField="UserName" DataValueField="InRole" />

In the code behind I have this code:

var usersInRole = new List<UserInRole> 
{ 
  new UserInRole { UserName = "Frank", InRole = false},
  new UserInRole{UserName = "Linda", InRole = true},
  new UserInRole{UserName = "James", InRole = true},
};

chkListRoles.DataSource = usersInRole;
chkListRoles.DataBind();

I was kinda hoping that the check boxes would be checked when InRole = true. I've also tried InRole = "Checked". The results were the same. I can't seem to find a way to DataBind and automagically have the check boxes checked/unchecked.

Currently I solve the problem by setting selected = true for the appropriate items in the DataBound event. Seems like there's a cleaner solution just beyond my grasp.

Thank You

A: 

I would think you would have to tell the control what property to bind it to...in this case "InRole".

I played around with it and seems like there is noway to bind to the selection of the checkbox, you have to do it yourself. I was able to bind to the text and values of the checklist which only seem to deal with the label of each checkbox in the list.

CSharpAtl
In the *.aspx file I declare the CheckBoxList with the attribute DataValueField="InRole". Is that what you mean?
Matthew Sposato
That is what I was talking about...I did not scroll to see you had set that in the UI code...sorry.
CSharpAtl
+3  A: 

EDIT: There's no way to do this through the Markup. The DataValueField does not determine whether the checkbox item is check or not. It retrieves or stores the value to be used in postbacks. The DataValueField is common across CheckBoxLists, RadioButtonLists, ListControl, etc.

This is about the only way to pre-select the checkboxes as you already found out.

chkListRoles.DataSource = usersInRole;
chkListRoles.DataBind();

foreach(ListItem item in chkListRoles.Items)
 item.Selected = usersInRole.Find(u => u.UserName == item.Text).InRole;
Jose Basilio
Thanks Jose, your answer clarifies the situation.
Matthew Sposato
Also thanks from me José, I'll be using that lambda ;-)
Mike Kingscott