my love hate relationship with the checkboxlist control

if you’re not a geek – you may want to turn your head at this point. this is going to be a fairly technical post.

i’m working on a website right now – can’t tell you much about it because it’s slightly one of those in progress, can’t talk about it much, type things. i’ve been working with asp:checkboxlist controls rather intensely over the last day or so. i’m going to document a few things here, in the hopes that they may help someone else – and because i know i’ll run into this again and need a point of reference. so, here goes:

so, you want to populate a checkboxlist with values from a database, eh? try something like this:

foreach (ListItem li in cblNewsCategories.Items)
(DataRow _Row in dsEditingForm.Tables[1].Rows
if (Convert.ToInt32(li.Value.ToString()) == Convert.ToInt32(_Row[“intCategoryID”].ToString()))
li.Selected = true;

this assumes that you have a rendered checkboxlist on the page, named cblNewsCategories. it also assumes that the values in the second table of the dataset built elsewhere in the method are essentially a link table in a fairly normalized database. for those who i’ve lost – let’s assume that there is a news table and a categories table which provide integer ID values as the shared primary key of this “imaginary” news-category table.

next. so, you want to put the checked values of a checkboxlist into an integer array which is only as large as the number of items in this array. try this:

int[] tempCategory = new int[0];

foreach (ListItem li in cblNewsCategories.Items)
if (li.Selected)
.Resize(ref tempCategory, tempCategory.Length + 1);
tempCategory.SetValue(Convert.ToInt32(li.Value.ToString()), tempCategory.Length – 1);

again, we have some assumptions. you have a checkboxlist on the page and there are some checked items in that list. you also must have a need to use an integer array. the first code sample is with help from a fellow developer from one of our partners. parts of the second came from an article which i cannot recall right now – and don’t have access to my browser history at work to find. i’ll try to cite that later if i remember.

so, if you find yourself hating checkboxlists like i did recently – maybe you can have some love for them after these tips. and, if you think this is elementary, bug off – i’m still learning.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s