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. =)

4 comments:

Dror Maor said...

I've been trying to figure this out for hours, but not until I came across your blog did I get it right! Thank you so much, and keep up the GREAT work!

Anonymous said...

That was very helpful.thank you.

AaronLS said...

I actually databind my controls in page_init so that viewstate is loaded afterwards. This means the selected status of the fields is restored. However, depending on how dynamic your page is, this may not work for everyone.

Anonymous said...

{palm to forehead} Thank you!