Yesterday the question was posted to the Arizona Groups list:
How do you have the selected values in an ASP.Net Listbox control scroll into view?
Simple answer: By default in IE whatever is selected does get scrolled to the top. In ASP.NET, the ListBox is rendered as a <SELECT> element with a SIZE attribute. For whatever item is selected, as appropriate the selected attribute gets applied. Here's an example to set the stage, both the HTML generated by ASP.NET and the actual control:
| |
<select name="listBox1" size="3" id="listBox1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> <option selected="selected" value="Yellow">Yellow</option> <option value="Cyan">Cyan</option> <option value="Magenta">Magenta</option> </select> |
So we see that by just setting the SelectedIndex property in ASP.NET then when it's presented in IE that member is scrolled into view and placed all the way at the top. Haven't tested it with other browsers, but I would bet in Mozilla and Safari it's similar behavior.
So now here's a button that uses Javascript to select and scroll the above ListBox to the “Green“ entry in the list:
In the onclick attribute it simply says "listBox1.selectedIndex=1;". Very easy.
Incidentally, with IE6 there is a scrollTop property which looks like it should set the amount a <SELECT> gets scrolled. But I don't know why it was even included because when referenced it always returns 0, and doesn't do anything when it's set. So perhaps in future versions of IE we'll be able to precisely set where things are scrolled using scrollTop in conjunction with selectedIndex, scrollHeight, and length.