Fixed Index for selected index in ListBox
Question:
Hi all experts,
I currently have a listbox that has 40 items inside and only 10 is visible at one time in my webpage as the size of the listbox is quite small.
As users select the items that are lower than the 10 visible (example with a index of 20), the page does a postback and the the listbox automatically returns to the top of the listbox thus users would have to scroll down again to see the selected index.
My question is: how do I maintain the selected index without the listbox automatically returning to the top after the page is refreshed? Is this possible?
Thank you all.
Best answer:
Hi abupapa ,
To use ajax is one good way , because it avoid post back.
But if you do not want to use ajax. You can write some javascript code to do this.
I think my code can give you some idea.
protected void Button1_Click(object sender, EventArgs e)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "aaa", "<script>setTimeout('dowork();',1);</script>");
}
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
function Button2_onclick() {
dowork();
}
function dowork()
{
var select = document.getElementById('ListBox1');
//select.scrollIntoView()
select[9].selected = true;
select[9].focus();
}
// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="Select1">
<option></option>
</select>
</div>
<asp:ListBox ID="ListBox1" runat="server" Height="55px"
SelectionMode="Multiple" Width="95px">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
<asp:ListItem>9</asp:ListItem>
<asp:ListItem>10</asp:ListItem>
</asp:ListBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>
<p>
<input id="Button2" type="button" value="button" onclick="return Button2_onclick()" /></p>
</body>
</html>