CheckBoxList.Selected always = False?

August 26, 2008

I’ve just spent a good 30 minutes trying to figure out why the following code would not output the values of selected items on a CheckBoxList

protected void Button1_Click(object sender, EventArgs e)
foreach (ListItem carCheckBox in CheckBoxList1.Items)
if (carCheckBox.Selected)

Turned out to be a very simple mistake – I was calling DataBind() on the CheckBoxList control on every page load, so Button1_Click was fired, causing the postback, the control was populated (and therefore no items were selected) following which the code within the click event ran, doing exactly as it should!

In case your wondering, the solution was to wrap the DataBind() (In page_load) in an if statement:

if (!IsPostBack) {

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

%d bloggers like this: