469,957 Members | 2,689 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,957 developers. It's quick & easy.

Selecting CheckBoxList Items when using DataBind

Had a tough time figuring this one out and couldn't find a good
solution, so I thought I would post this and hopefully it will help
someone out.

When using DataBind to dynamically bind a list to the CheckBoxList
control in ASP .NET, I had a hard time figuring out how to dynamically
select the items that needed to be selected. Specifically, I was
displaying checkboxes for Roles, and I wanted to check the boxes of
the roles that were currently assigned to the user.

I used the OnDataBound event in my CheckBoxList to call a selectBoxes
method. In my selectBoxes method, I was able to get the collection of
Items in the CheckBoxList and loop through them, selecting the ones
that needed to be selected.

Here is my CheckBoxList tag in the .aspx file:

<asp:CheckBoxList ID="rolesCheckBoxes" runat="server"

And here is the method selectBoxes that gets called OnDataBound in the
code behind:

public void selectBoxes(object sender, EventArgs e) {
//call this out here instead of Roles.isUserInRole
//because isUserInRole makes a DB call each time
string[] roles = Roles.GetRolesForUser("username");
foreach (ListItem l in ((CheckBoxList)sender).Items) {
foreach (string role in roles) {
if (role == l.Text) {
l.Selected = true;

The key for me was to cast the 'sender' variable as a CheckBoxList
object, and then use the Items property to loop through each
individual checkbox in the list. Sweet!


Feb 16 '07 #1
0 10840

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by sql | last post: by
3 posts views Thread by I am Sam | last post: by
4 posts views Thread by Patrick.O.Ige | last post: by
2 posts views Thread by Patrick.O.Ige | last post: by
6 posts views Thread by dbuchanan | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.