Adsense

Monday, December 22, 2008

Databinding an asp:ListBox has no selected items (selected = false)

If you are working with a Data Bound ASP.Net ListBox control (or a similar control) and are having trouble with all of your ListItem.Selected calls are returning false even though you KNOW you selected one or more of them. You might have an issue with the way you're Data Binding.

Consider the following code. In my example I am using a DataBindControls method that will retrieve some data and then bind it to a ListBox.

private void DataBindControls() {
ArrayList roles = RoleProvider.Instance().GetRoles();

lbRoles.DataSource = roles;
lbRoles.DataTextField = "RoleName";
lbRoles.DataValueField = "RoleId";
lbRoles.DataBind();
}

I just so happen to be calling this method in the Page_Load even of my page. Unfortunately, I forgot to wrap this call in a "IsPostBack" check. What is happening is that my control is being databound again before I access the selected values from the previous request.

protected void Page_Load(object sender, EventArgs e) {
DataBindControls();
}

You can easily remedy this issue by wrapping the call in an if statement that makes sure to only databind your controls on the initial call to the page. (when it's not a post back)

protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
DataBindControls();
}
}

Just another one of those "Palm to Forhead" issues. Hope it helps someone. =)