Show Selected Item in Listbox (System.Web.UI.WebControls)
I'm working with a listbox that has, let's say, 20 items. The size of the listbox allows the user to see the first 5 items. However, the listbox has one preselected item which is sometimes not visible because it isn't one of the first 5 items.
After I set the selected Item for the listbox how can I ensure that the lisbox is scrolled ap开发者_如何学编程propriately so that the selected item is visible to the user?
Thanks for your help!
Have you tried to set the TopIndex property?
listBox.TopIndex = itemIndex;
Sorry, my first understanding of your question was completely wrong. I think you can do it by using javascript. I tested the sample below on Windows 7 and IE8 and it worked.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function setSelectedIndex() {
            var listBox = $get('listBox');
            var textBox = $get('textBox');
            listBox.selectedIndex = textBox.value;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:ListBox runat="server" ID="listBox">
            <asp:ListItem Text="A" Value="A" />
            <asp:ListItem Text="B" Value="B" />
            <asp:ListItem Text="C" Value="C" />
            <asp:ListItem Text="D" Value="D" />
            <asp:ListItem Text="E" Value="E" />
            <asp:ListItem Text="F" Value="F" />
            <asp:ListItem Text="G" Value="G" />
            <asp:ListItem Text="H" Value="H" />
            <asp:ListItem Text="I" Value="I" />
            <asp:ListItem Text="K" Value="K" />
        </asp:ListBox>
        <asp:TextBox runat="server" ID="textBox" Text="8" />
        <asp:Button runat="server" ID="button" Text="Select" OnClientClick="setSelectedIndex(); return false;" />
    </div>
    </form>
</body>
</html>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论