Thursday, April 7, 2011

Setting ListBox scroll position at the Selected Items

If you have a listbox inside your user control and if all of these conditions below apply:
1. Your listbox is inside a user control
2. The user control becomes visible based on other selections on the webform you made.
3. The listbox is bound to the data in the Page_Init and the default SelectedValue is set in the code behind.

In this scenario, when the user control becomes visible, the listbox scroll position is set at the first item in the listbox instead of at the SelectedValue.

If you want the listbox scroll position at the SelectedValue, you have to write javascript.

Write this javascript in your user control:

window.onload = function () {
var ddl = document.getElementById('<%=DDL.ClientID%>');
len = ddl.length;
for (var j = 0; j < len; j++) {
if (ddl.options[j].selected) {
ddl.options[j].selected = false;
ddl.options[j].selected = true;
}
}
}

What you do here is just unselect and reselect the selected items.

No comments: