JackWilson
JackWilson

Reputation: 577

DataBind() on CheckBoxList: Problem with getting .Selected

I'm new to C# and ASP.NET.

I have a CheckBoxList named DeploySelectList. If I manually add items to the list as follows, I have no problems getting the .Selected items after the Submit button is clicked.

protected void Page_Load(object sender, EventArgs e) {
        DeploySelectList.Items.Add("test 1");
        DeploySelectList.Items.Add("test 2");
        DeploySelectList.Items.Add("test 3");
}

However, if I create a DataBinding to a List object, all DeploySelectList items always have .Selected = false.

protected void Page_Load(object sender, EventArgs e) {
        List<String> list = DBFunctions.getDeploymentSelection();
        DeploySelectList.DataSource = list;
        DeploySelectList.DataBind();
}

Why would this be happening?

Thanks.

EDIT: As per the comment below, adding the code in an if (!IsPostBack) block fixed the problem. I still don't understand why the problem was not the same when doing it manually vs. doing the DataBinding. It seems that in both cases the selection should be lost.

Should this question be deleted?

Upvotes: 1

Views: 1060

Answers (1)

Kevin Burton
Kevin Burton

Reputation: 11934

The link below shows you the order that the page events are fired.

http://msdn.microsoft.com/en-us/library/ms178472.aspx

And as already mentioned you need to stop rebuilding the list on postback in the page load. so that you can check the selected property when the event code is executed.

Upvotes: 1

Related Questions